local COLOR_UNREGISTERED = {.3, .3, 1, .7}
local COLOR_REGISTERED = {.3, 1, .3, .7}
local COLOR_SELECTED = {1, .3, .6, .7}
local COLOR_BORDER_SELECTED = {1, 1, 0, 1}
local COLOR_BORDER_DESELECTED = {1, 1, 1, 1}
local MIN_SIZE = 30
local COLUMN_WIDTH = 162
local COVER_BUTTON_BACKDROP = {bgFile = "Interface/Tooltips/UI-Tooltip-Background", edgeFile = "Interface/Buttons/WHITE8X8", edgeSize=1}
local SLIDER_VALUE_NA = "-"
local TRIGGER = "trigger"
local FIELD = "field"
local TITLE = "title"
local TOOLTIP = "tooltip"
local OWNER = "owner"
local VALID = "valid"
local FRAME = "frame"

local FADE_OUT_TIME = "Fade Out Time (sec)"
local FADE_IN_TIME = "Fade In Time (sec)"
local SHOWN_ALPHA = "Shown Alpha"

KongConfig_SelectedFrames = {}
KongConfig_Frames = {}
KongConfig_NumFrames = 0

local ConfigTriggerDefaults = {
secondsIn = .2,
secondsOut = 1,
alphaIn = 1,
alphaOut = 0,
}
tinsert(KONG_TRIGGER_NAMES, "config")
  
function KongConfig_CommandHandler(input)

    local args = {strsplit(" ", string.lower(input))}
    local command = args[1]
    
    if command == "" then
        KongConfig_Show()
    else
        if KongConfig and KongConfig.frame:IsShown() then 
            Kong_Error("The config screen must be closed to issue /kong commands.")
        else
            Kong_CommandHandler(input)
        end
    end
end
SlashCmdList["KONG"] = KongConfig_CommandHandler

function KongConfig_Error(str, ...)
    KongConfig:SetStatusText("|cFFFF2222Error:|r "..string.format(str, ...))
end

function KongConfig_Warning(str, ...)
    KongConfig:SetStatusText("|cFFFF9922Warning:|r "..string.format(str, ...))
end

local function Debracket(str)

    str = gsub(str, "%[\"", ".")
    str = gsub(str, "\"%]", "")
    return string.sub(str, 2)
end                    

local Kong_ErrorOriginal
local Kong_WarningOriginal
function KongConfig_Show()

    KongConfig_InitComponents()
    KongConfig:Show()
    
    -- Create the cover buttons
    for i,child in pairs({UIParent:GetChildren()}) do
        if not child:IsObjectType("GameTooltip") then
            if child:IsShown() and child ~= KongConfig.frame then
                local configName = "KongConfig_"..(child:GetName() or tostring(child))
                if not KongConfig_Frames[configName] then
                    local CoverButton = CreateFrame("Button", configName)
                    CoverButton:SetFrameStrata("DIALOG")
                    CoverButton:SetFrameLevel(KongConfig_NumFrames)
                    CoverButton:SetBackdrop(COVER_BUTTON_BACKDROP)
                    CoverButton:SetHighlightTexture("Interface\\FullScreenTextures\\OutOfControl", "ADD");
                    CoverButton.uiFrame = child
                    
                    -- Mouse wheel used to change frame level
                    CoverButton:EnableMouseWheel(true)
                    CoverButton:SetScript("OnMouseWheel", KongConfig_CoverButton_OnMouseWheel)
                    
                    CoverButton:SetScript("OnClick", KongConfig_CoverButton_OnClick)
                    
                    local text1 = CoverButton:CreateFontString(configName.."Title", "ARTWORK", "GameFontNormal")
                    text1:SetPoint("CENTER")
                    text1:SetTextColor(1, 1, 1, 1)
                    if Kong_Frames[child] then
                        text1:SetText(Debracket(Kong_Frames[child].index))
                    else
                        text1:SetText(Debracket(Kong_FindGlobalIndex(child) or " <noname>"))
                    end
                    
                    KongConfig_Frames[configName] = CoverButton
                    KongConfig_NumFrames = KongConfig_NumFrames + 1
                else
                    KongConfig_Frames[configName]:Show()
                end
                
                -- Distinguish between registered and unregistered frames
                if KongConfig_SelectedFrames[KongConfig_Frames[configName]] then
                    KongConfig_Frames[configName]:SetBackdropColor(unpack(COLOR_SELECTED))
                elseif Kong_Frames[child] then 
                    KongConfig_Frames[configName]:SetBackdropColor(unpack(COLOR_REGISTERED))
                else
                    KongConfig_Frames[configName]:SetBackdropColor(unpack(COLOR_UNREGISTERED))
                end
                
                -- Expand config frame if too small
                local xoff, yoff = 0, 0
                if child:GetWidth() < MIN_SIZE then
                    xoff = (MIN_SIZE-child:GetWidth())/2
                end
                if child:GetHeight() < MIN_SIZE then
                    yoff = (MIN_SIZE-child:GetHeight())/2
                end
                KongConfig_Frames[configName]:SetPoint("TOPLEFT", child, "TOPLEFT", -xoff, yoff)
                KongConfig_Frames[configName]:SetPoint("BOTTOMRIGHT", child, "BOTTOMRIGHT", xoff, -yoff)
            end
        end
    end
    
    -- Deselect any frames that are no longer onscreen for configuration
    for _, PreviouslySelectedFrame in pairs(KongConfig_SelectedFrames) do
        if not PreviouslySelectedFrame:IsShown() then
            KongConfig_SelectedFrames[PreviouslySelectedFrame] = nil
        end
    end
    
    -- Make sure the config frame is on top
    KongConfig.frame:SetFrameLevel(KongConfig_NumFrames)
    
    -- Display registered frames
    for Root, Kong in pairs(Kong_Frames) do
        Kong.config = Kong_TriggerFactory.Create(ConfigTriggerDefaults)
        Kong_FadeIn(Root, Kong.config)
    end
    
    -- Update the config widgets' states
    KongConfig_UpdateComponents()
    
    -- Redirect errors and warnings to the status bar
    Kong_ErrorOriginal = Kong_Error
    Kong_Error = KongConfig_Error
    Kong_WarningOriginal = Kong_Warning
    Kong_Warning = KongConfig_Warning
end

function KongConfig_ToggleChecked(self)
    local value = self:GetValue()
    if self.tristate then
        --cycle in false, nil, true order
        if value then
            self:SetValue(false)
        elseif value == nil then
            self:SetValue(true)
        else
            self:SetValue(nil)
        end
    else
        self:SetValue(not self:GetValue())
    end
end

local function NegateBoolean(value)

    if string.sub(value, 1, 2) == "no" then
        return string.sub(value, 3)
    else
        return "no"..value
    end
end

local AceGUI = LibStub("AceGUI-3.0")
function KongConfig_InitComponents()

    if not KongConfig then
    
        -- Create a container frame
        KongConfig = AceGUI:Create("Frame")
        KongConfig:SetTitle("Kong Configuration")
        KongConfig:SetStatusText("Status Bar")
        KongConfig:SetLayout("Flow")
        KongConfig:SetWidth(400)
        KongConfig:SetHeight(435)
        KongConfig:SetStatusText("")
        KongConfig.frame:SetScript("OnUpdate", KongConfig_OnUpdate);
        KongConfig.frame:SetMinResize(400, 200)
        KongConfig.LayoutFinished = function(self)
            KongConfig_FadeCheckBox:ClearAllPoints();
            KongConfig_FadeCheckBox:SetPoint("TOP")
        end
        tinsert(UISpecialFrames, "KongConfig")
        
        -- Make it opaque
        local kongback = KongConfig.frame:GetBackdrop()
        kongback.bgFile = "Interface\\ChatFrame\\ChatFrameBackground"
        KongConfig.frame:SetBackdrop(kongback)
        KongConfig.frame:SetBackdropColor(0, 0, 0, 1)

        -- Register for cleanup
        KongConfig:SetCallback("OnClose", KongConfig_OnClose)

        -- Fade CheckBox
        KongConfig_FadeCheckBox = AceGUI:Create("CheckBox")
        KongConfig_FadeCheckBox:SetWidth(168)
        KongConfig_FadeCheckBox.text:SetJustifyH("RIGHT")
        KongConfig_FadeCheckBox:SetLabel("Fade Selected Frame(s)")
        KongConfig_FadeCheckBox:SetCallback("OnValueChanged", KongConfig_FadeCheckBox_OnValueChanged)
        KongConfig_FadeCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
        KongConfig_FadeCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
        KongConfig_FadeCheckBox:SetUserData(TOOLTIP, "Registers the selected widget(s) to be controlled by Kong")
        KongConfig_FadeCheckBox.ToggleChecked = KongConfig_ToggleChecked
        
        -- Scroll pane
        KongConfig_ScrollFrame = AceGUI:Create("ScrollFrame")
        KongConfig_ScrollFrame:SetFullWidth(true)
        KongConfig_ScrollFrame:SetLayout("List")
        
        KongConfig_InitDefaultComponents()
        KongConfig_ScrollFrame:AddChild(KongConfig_DefaultsGroup)
        
        KongConfig_InitCombatComponents()
        KongConfig_ScrollFrame:AddChild(KongConfig_CombatGroup)
        
        KongConfig_InitVehicleComponents()        
        KongConfig_ScrollFrame:AddChild(KongConfig_VehicleGroup)

        KongConfig_InitHealthComponents()
        KongConfig_ScrollFrame:AddChild(KongConfig_HealthGroup)
        
        KongConfig_InitPowerComponents()
        --KongConfig_ScrollFrame:AddChild(KongConfig_PowerGroup)
        
        KongConfig_InitCastingComponents()
        KongConfig_ScrollFrame:AddChild(KongConfig_CastingGroup)
        
        KongConfig_InitMacroComponents()
        KongConfig_ScrollFrame:AddChild(KongConfig_MacroGroup)
        
        KongConfig_InitMouseoverComponents()
        KongConfig_ScrollFrame:AddChild(KongConfig_MouseoverGroup)
        
        KongConfig_InitMouseoverGroupComponents()
        KongConfig_ScrollFrame:AddChild(KongConfig_MouseoverGroupsGroup)
        
        KongConfig_InitAdvancedComponents()
        KongConfig_ScrollFrame:AddChild(KongConfig_AdvancedGroup)
        
        KongConfig_ScrollGroup = AceGUI:Create("SimpleGroup")
        KongConfig_ScrollGroup:SetFullWidth(true)
        KongConfig_ScrollGroup:SetFullHeight(true)
        KongConfig_ScrollGroup:SetLayout("Fill")
        KongConfig_ScrollGroup.frame:SetBackdrop({
            bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
            edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
            tile = true, tileSize = 16, edgeSize = 16,
            insets = { left = 3, right = 3, top = 5, bottom = 3 }
        })
        KongConfig_ScrollGroup.frame:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
        KongConfig_ScrollGroup.frame:SetBackdropBorderColor(0.4, 0.4, 0.4)
        KongConfig_ScrollGroup.content:SetPoint("TOPLEFT", 10, -10)
        KongConfig_ScrollGroup.content:SetPoint("BOTTOMRIGHT", -10, 10)  
        KongConfig_ScrollGroup:AddChild(KongConfig_ScrollFrame)    
        
        -- Main panel
        KongConfig:AddChild(KongConfig_FadeCheckBox)
        KongConfig:AddChild(KongConfig_ScrollGroup)
		
        KongConfig_AutoExpandAndCollapse()
    end
    
    -- Set the inital state of these widgets
    KongConfig_UpdateComponents() 
end

function KongConfig_InitDefaultComponents()

    KongConfig_DefaultsGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_DefaultsGroup:SetFullWidth(true)
    KongConfig_DefaultsGroup:SetLayout("Flow")
    KongConfig_DefaultsGroup:SetText("Defaults")
    
    -- Hidden Alpha
    KongConfig_HiddenAlphaCheckBox, KongConfig_HiddenAlphaSlider, KongConfig_HiddenAlphaGroup = 
        KongConfig_CreateTriggerSliderGroup("Hidden Alpha", "TriggerDefaults", "alphaOut", 
        "The transparency of the selected widget(s) when hidden by Kong")
    KongConfig_HiddenAlphaSlider:SetIsPercent(true)
    KongConfig_HiddenAlphaSlider:SetSliderValues(0, 1, .01)
    
    
    -- Shown Alpha
    KongConfig_ShownAlphaCheckBox, KongConfig_ShownAlphaSlider, KongConfig_ShownAlphaGroup = 
        KongConfig_CreateTriggerSliderGroup(SHOWN_ALPHA, "TriggerDefaults", "alphaIn",
        "The default transparency of the selected widget(s) when shown by Kong. This can be overridden in the sections below.")
    KongConfig_ShownAlphaSlider:SetIsPercent(true)
    KongConfig_ShownAlphaSlider:SetSliderValues(0, 1, .01)
    
    -- Fade In
    KongConfig_FadeInCheckBox, KongConfig_FadeInSlider, KongConfig_FadeInGroup = 
        KongConfig_CreateTriggerSliderGroup(FADE_IN_TIME, "TriggerDefaults", "secondsIn", 
        "The default duration over which to fade in the selected widget(s). This can be overridden in the sections below.")
    KongConfig_FadeInSlider:SetSliderValues(0, 10, .1)

    -- Fade Out
    KongConfig_FadeOutCheckBox, KongConfig_FadeOutSlider, KongConfig_FadeOutGroup = 
        KongConfig_CreateTriggerSliderGroup(FADE_OUT_TIME, "TriggerDefaults", "secondsOut",
        "The default duration over which to fade out the selected widget(s). This can be overridden in the sections below.")
    KongConfig_FadeOutSlider:SetSliderValues(0, 10, .1)

    KongConfig_DefaultsGroup:AddChild(KongConfig_HiddenAlphaGroup)
    KongConfig_DefaultsGroup:AddChild(KongConfig_ShownAlphaGroup)
    KongConfig_DefaultsGroup:AddChild(KongConfig_FadeInGroup)
    KongConfig_DefaultsGroup:AddChild(KongConfig_FadeOutGroup)
end

function KongConfig_InitCombatComponents()

    KongConfig_CombatGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_CombatGroup:SetFullWidth(true)
    KongConfig_CombatGroup:SetLayout("Flow")
    KongConfig_CombatGroup:SetText("Combat")
       
    -- Combat CheckBoxes
    KongConfig_CombatShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_CombatShowCheckBox:SetLabel("Show in Combat")
    KongConfig_CombatShowCheckBox:SetCallback("OnValueChanged", KongConfig_ShowBooleanRadioButton_OnValueChanged)
    KongConfig_CombatShowCheckBox:SetUserData(TRIGGER, "combat")
    KongConfig_CombatShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) while in combat")
    KongConfig_CombatShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_CombatShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_CombatShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    KongConfig_NocombatShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_NocombatShowCheckBox:SetLabel("Show out of Combat")
    KongConfig_NocombatShowCheckBox:SetCallback("OnValueChanged", KongConfig_ShowBooleanRadioButton_OnValueChanged)
    KongConfig_NocombatShowCheckBox:SetUserData(TRIGGER, "nocombat")
    KongConfig_NocombatShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_NocombatShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_NocombatShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) while out of combat")
    KongConfig_NocombatShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    KongConfig_CombatRadioButtonGroup = AceGUI:Create("SimpleGroup")
    KongConfig_CombatRadioButtonGroup:SetWidth(COLUMN_WIDTH)
    KongConfig_CombatRadioButtonGroup:SetLayout("Flow")
    KongConfig_CombatRadioButtonGroup:AddChild(KongConfig_CombatShowCheckBox)
    KongConfig_CombatRadioButtonGroup:AddChild(KongConfig_NocombatShowCheckBox)
     
    -- Combat Alpha
    KongConfig_CombatAlphaCheckBox, KongConfig_CombatAlphaSlider, KongConfig_CombatAlphaGroup =
        KongConfig_CreateTriggerSliderGroup(SHOWN_ALPHA, "combat", "alphaIn",
        "The transparency of the selected widget(s) while in combat",
        "The transparency of the selected widget(s) while out of combat")
    KongConfig_CombatAlphaSlider:SetIsPercent(true)
    KongConfig_CombatAlphaSlider:SetSliderValues(0, 1, .01)
      
    -- Combat Fade In
    KongConfig_CombatFadeInCheckBox, KongConfig_CombatFadeInTimeSlider, KongConfig_CombatFadeInGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_IN_TIME, "combat", "secondsIn",
        "The duration over which to fade in the selected widget(s) when entering combat",
        "The duration over which to fade in the selected widget(s) when leaving combat")
    KongConfig_CombatFadeInTimeSlider:SetSliderValues(0, 10, .1)

    -- Combat Fade Out
    KongConfig_CombatFadeOutCheckBox, KongConfig_CombatFadeOutTimeSlider, KongConfig_CombatFadeOutGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_OUT_TIME, "combat", "secondsOut",
        "The duration over which to fade out the selected widget(s) when leaving combat",
        "The duration over which to fade out the selected widget(s) when entering combat")
    KongConfig_CombatFadeOutTimeSlider:SetSliderValues(0, 10, .1)
    
    KongConfig_CombatGroup:AddChild(KongConfig_CombatRadioButtonGroup)
    KongConfig_CombatGroup:AddChild(KongConfig_CombatAlphaGroup)
    KongConfig_CombatGroup:AddChild(KongConfig_CombatFadeInGroup)
    KongConfig_CombatGroup:AddChild(KongConfig_CombatFadeOutGroup)
end

function KongConfig_InitVehicleComponents()

    KongConfig_VehicleGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_VehicleGroup:SetFullWidth(true)
    KongConfig_VehicleGroup:SetLayout("Flow")
    KongConfig_VehicleGroup:SetText("Vehicle")
    
    -- Vehicle CheckBoxes
    KongConfig_VehicleShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_VehicleShowCheckBox:SetLabel("Show in Vehicle")
    KongConfig_VehicleShowCheckBox:SetCallback("OnValueChanged", KongConfig_ShowBooleanRadioButton_OnValueChanged)
    KongConfig_VehicleShowCheckBox:SetUserData(TRIGGER, "vehicle")
    KongConfig_VehicleShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) while in a vehicle")
    KongConfig_VehicleShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_VehicleShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_VehicleShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    KongConfig_NovehicleShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_NovehicleShowCheckBox:SetLabel("Show out of Vehicle")
    KongConfig_NovehicleShowCheckBox:SetCallback("OnValueChanged", KongConfig_ShowBooleanRadioButton_OnValueChanged)
    KongConfig_NovehicleShowCheckBox:SetUserData(TRIGGER, "novehicle")
    KongConfig_NovehicleShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) while not in a vehicle")
    KongConfig_NovehicleShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_NovehicleShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_NovehicleShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    KongConfig_VehicleRadioButtonGroup = AceGUI:Create("SimpleGroup")
    KongConfig_VehicleRadioButtonGroup:SetWidth(COLUMN_WIDTH)
    KongConfig_VehicleRadioButtonGroup:SetLayout("Flow")
    KongConfig_VehicleRadioButtonGroup:AddChild(KongConfig_VehicleShowCheckBox)
    KongConfig_VehicleRadioButtonGroup:AddChild(KongConfig_NovehicleShowCheckBox)
     
    -- Vehicle Alpha
    KongConfig_VehicleAlphaCheckBox, KongConfig_VehicleAlphaSlider, KongConfig_VehicleAlphaGroup =
        KongConfig_CreateTriggerSliderGroup(SHOWN_ALPHA, "vehicle", "alphaIn",
        "The transparency of the selected widget(s) while in a vehicle",
        "The transparency of the selected widget(s) while not in a vehicle")
    KongConfig_VehicleAlphaSlider:SetIsPercent(true)
    KongConfig_VehicleAlphaSlider:SetSliderValues(0, 1, .01)
      
    -- Vehicle Fade In
    KongConfig_VehicleFadeInCheckBox, KongConfig_VehicleFadeInTimeSlider, KongConfig_VehicleFadeInGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_IN_TIME, "vehicle", "secondsIn",
        "The duration over which to fade in the selected widget(s) when entering a vehicle",
        "The duration over which to fade in the selected widget(s) when leaving a vehicle")
    KongConfig_VehicleFadeInTimeSlider:SetSliderValues(0, 10, .1)

    -- Vehicle Fade Out
    KongConfig_VehicleFadeOutCheckBox, KongConfig_VehicleFadeOutTimeSlider, KongConfig_VehicleFadeOutGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_OUT_TIME, "vehicle", "secondsOut",
        "The duration over which to fade out the selected widget(s) when leaving a vehicle",
        "The duration over which to fade out the selected widget(s) when entering a vehicle")
    KongConfig_VehicleFadeOutTimeSlider:SetSliderValues(0, 10, .1)
    
    KongConfig_VehicleGroup:AddChild(KongConfig_VehicleRadioButtonGroup)
    KongConfig_VehicleGroup:AddChild(KongConfig_VehicleAlphaGroup)
    KongConfig_VehicleGroup:AddChild(KongConfig_VehicleFadeInGroup)
    KongConfig_VehicleGroup:AddChild(KongConfig_VehicleFadeOutGroup)
end

function KongConfig_InitHealthComponents()

    KongConfig_HealthGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_HealthGroup:SetFullWidth(true)
    KongConfig_HealthGroup:SetLayout("Flow")
    KongConfig_HealthGroup:SetText("Health")
    
    -- Checkbox
    KongConfig_HealthShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_HealthShowCheckBox:SetLabel("Show when Health of")
    KongConfig_HealthShowCheckBox:SetWidth(COLUMN_WIDTH)
    KongConfig_HealthShowCheckBox:SetHeight(15)
    KongConfig_HealthShowCheckBox.frame:SetHitRectInsets(0,0,0,-5)
    KongConfig_HealthShowCheckBox:SetUserData(TRIGGER, "health")
    KongConfig_HealthShowCheckBox:SetCallback("OnValueChanged", KongConfig_PowerShowCheckBox_OnValueChanged)
    KongConfig_HealthShowCheckBox:SetUserData(TITLE, "Show when Health of...")
    KongConfig_HealthShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) when the health of one or more units matches the specified criteria")
    KongConfig_HealthShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_HealthShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_HealthShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    -- Unit
    KongConfig_HealthUnitsComboBox = AceGUI:Create("Dropdown")
    KongConfig_HealthUnitsComboBox:SetWidth(COLUMN_WIDTH-52)
    KongConfig_HealthUnitsComboBox:SetHeight(-48)
    KongConfig_HealthUnitsComboBox:SetMultiselect(true)
    KongConfig_HealthUnitsComboBox:SetList(Kong_PowerUnits)
    KongConfig_HealthUnitsComboBox:SetUserData(TRIGGER, "health")
    KongConfig_HealthUnitsComboBox:SetCallback("OnValueChanged", KongConfig_PowerUnitsComboBox_OnValueChanged)
    KongConfig_HealthUnitsComboBox:SetUserData(TITLE, "Health of Unit(s) Dropdown")
    KongConfig_HealthUnitsComboBox:SetUserData(TOOLTIP, "The unit(s) that will cause the selected widget(s) to fade in whenever any of their healths match the specified condition")
    KongConfig_HealthUnitsComboBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_HealthUnitsComboBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_HealthUnitsComboBox.pullout.frame:Hide()
    
    
    -- Less than or Greater than
    KongConfig_HealthComparisonComboBox = AceGUI:Create("Dropdown")
    KongConfig_HealthComparisonComboBox:SetWidth(50)
    KongConfig_HealthComparisonComboBox:SetHeight(-48)
    KongConfig_HealthComparisonComboBox:SetList({"<",">"})
    KongConfig_HealthComparisonComboBox:SetUserData(TRIGGER, "health")
    KongConfig_HealthComparisonComboBox:SetCallback("OnValueChanged", KongConfig_PowerComparisonComboBox_OnValueChanged)
    KongConfig_HealthComparisonComboBox:SetUserData(TITLE, "Health Less Than or Greater Than Dropdown")
    KongConfig_HealthComparisonComboBox:SetUserData(TOOLTIP, "Determines if the selected widget(s) fade in when health is above or below the specified amount")
    KongConfig_HealthComparisonComboBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_HealthComparisonComboBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_HealthComparisonComboBox.pullout.frame:Hide()
    KongConfig_HealthComparisonComboBox.pullout:SetCallback("OnOpen", function(self)
		self.open = true
    end)
    
    -- Health Threshold
    KongConfig_HealthThresholdSlider = AceGUI:Create("Slider")
    KongConfig_HealthThresholdSlider:SetWidth(COLUMN_WIDTH)
    KongConfig_HealthThresholdSlider:SetIsPercent(true)
    KongConfig_HealthThresholdSlider:SetSliderValues(0, 1, .01)
    KongConfig_HealthThresholdSlider:SetUserData(TRIGGER, "health")
    KongConfig_HealthThresholdSlider:SetUserData(FIELD, "threshold")
    KongConfig_HealthThresholdSlider:SetCallback("OnMouseUp", KongConfig_PowerThresholdSlider_OnMouseUp)
    KongConfig_HealthThresholdSlider:SetUserData(TITLE, "Health Threshold")
    KongConfig_HealthThresholdSlider:SetUserData(TOOLTIP, "The amount of health which will cause the selected widget(s) to fade in")
    KongConfig_HealthThresholdSlider:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_HealthThresholdSlider:SetCallback("OnLeave", KongConfig_UpdateTooltip)
     
    -- Settings Group
    KongConfig_HealthSettingsGroup = AceGUI:Create("SimpleGroup")
    KongConfig_HealthSettingsGroup:SetWidth(COLUMN_WIDTH)
    KongConfig_HealthSettingsGroup:SetLayout("Flow")
    KongConfig_HealthSettingsGroup:AddChild(KongConfig_HealthShowCheckBox)
    KongConfig_HealthSettingsGroup:AddChild(KongConfig_HealthUnitsComboBox)
    KongConfig_HealthSettingsGroup:AddChild(KongConfig_HealthComparisonComboBox)
    KongConfig_HealthSettingsGroup:AddChild(KongConfig_HealthThresholdSlider)
     
    KongConfig_HealthShowCheckBox:SetUserData(OWNER, KongConfig_HealthSettingsGroup.frame)
    KongConfig_HealthUnitsComboBox:SetUserData(OWNER, KongConfig_HealthSettingsGroup.frame)
    KongConfig_HealthComparisonComboBox:SetUserData(OWNER, KongConfig_HealthSettingsGroup.frame)
    KongConfig_HealthThresholdSlider:SetUserData(OWNER, KongConfig_HealthSettingsGroup.frame)
    
    -- Health Alpha
    KongConfig_HealthAlphaCheckBox, KongConfig_HealthAlphaSlider, KongConfig_HealthAlphaGroup =
        KongConfig_CreateTriggerSliderGroup(SHOWN_ALPHA, "health", "alphaIn",
        "The transparency of the selected widget(s) while the given health condition is met")
    KongConfig_HealthAlphaSlider:SetIsPercent(true)
    KongConfig_HealthAlphaSlider:SetSliderValues(0, 1, .01)
      
    -- Health Fade In
    KongConfig_HealthFadeInCheckBox, KongConfig_HealthFadeInTimeSlider, KongConfig_HealthFadeInGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_IN_TIME, "health", "secondsIn",
        "The duration over which to fade in the selected widget(s) when the given health condition is met")
    KongConfig_HealthFadeInTimeSlider:SetSliderValues(0, 10, .1)

    -- Health Fade Out
    KongConfig_HealthFadeOutCheckBox, KongConfig_HealthFadeOutTimeSlider, KongConfig_HealthFadeOutGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_OUT_TIME, "health", "secondsOut",
        "The duration over which to fade out the selected widget(s) when the given health condition is no longer met")
    KongConfig_HealthFadeOutTimeSlider:SetSliderValues(0, 10, .1)
    
    KongConfig_HealthGroup:AddChild(KongConfig_HealthSettingsGroup)
    KongConfig_HealthGroup:AddChild(KongConfig_HealthAlphaGroup)
    KongConfig_HealthGroup:AddChild(KongConfig_HealthFadeInGroup)
    KongConfig_HealthGroup:AddChild(KongConfig_HealthFadeOutGroup)
end

function KongConfig_InitPowerComponents()

    KongConfig_PowerGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_PowerGroup:SetFullWidth(true)
    KongConfig_PowerGroup:SetLayout("Flow")
    KongConfig_PowerGroup:SetText("Power")
    
    -- Checkbox
    KongConfig_PowerShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_PowerShowCheckBox:SetLabel("Show when the")
    KongConfig_PowerShowCheckBox:SetWidth(COLUMN_WIDTH-52)
    --KongConfig_PowerShowCheckBox:SetHeight(15)
    KongConfig_PowerShowCheckBox.frame:SetHitRectInsets(0,0,0,-5)
    KongConfig_PowerShowCheckBox:SetUserData(TRIGGER, "power")
    KongConfig_PowerShowCheckBox:SetCallback("OnValueChanged", KongConfig_PowerShowCheckBox_OnValueChanged)
    KongConfig_PowerShowCheckBox:SetUserData(TITLE, "Show when the Power of...")
    KongConfig_PowerShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) when the power type(s) of one or more units matches the specified criteria")
    KongConfig_PowerShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_PowerShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_PowerShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    -- Power type
    KongConfig_PowerTypesComboBox = AceGUI:Create("Dropdown")
    KongConfig_PowerTypesComboBox:SetLabel(" ");
    KongConfig_PowerTypesComboBox:SetWidth(COLUMN_WIDTH+25)
    KongConfig_PowerTypesComboBox:SetHeight(25)
    KongConfig_PowerTypesComboBox:SetMultiselect(true)
    KongConfig_PowerTypesComboBox:SetList(Kong_PowerTypes)
    KongConfig_PowerTypesComboBox:SetUserData(TRIGGER, "power")
    KongConfig_PowerTypesComboBox:SetCallback("OnValueChanged", KongConfig_PowerTypesComboBox_OnValueChanged)
    KongConfig_PowerTypesComboBox:SetUserData(TITLE, "Power Type Dropdown")
    KongConfig_PowerTypesComboBox:SetUserData(TOOLTIP, "The type(s) of power that will cause the selected widget(s) to fade in whenever they match the specified condition")
    KongConfig_PowerTypesComboBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_PowerTypesComboBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_PowerTypesComboBox.pullout.frame:Hide()
   
    -- "of" label
    KongConfig_PowerOfLabel = AceGUI:Create("Label")
    KongConfig_PowerOfLabel:SetText("  of");
    KongConfig_PowerOfLabel:SetWidth(23)
    
    -- Unit
    KongConfig_PowerUnitsComboBox = AceGUI:Create("Dropdown")
    KongConfig_PowerUnitsComboBox:SetWidth(COLUMN_WIDTH-52)
    KongConfig_PowerUnitsComboBox:SetHeight(-48)
    KongConfig_PowerUnitsComboBox:SetMultiselect(true)
    KongConfig_PowerUnitsComboBox:SetList(Kong_PowerUnits)
    KongConfig_PowerUnitsComboBox:SetUserData(TRIGGER, "power")
    KongConfig_PowerUnitsComboBox:SetCallback("OnValueChanged", KongConfig_PowerUnitsComboBox_OnValueChanged)
    KongConfig_PowerUnitsComboBox:SetUserData(TITLE, "Power of Unit(s) Dropdown")
    KongConfig_PowerUnitsComboBox:SetUserData(TOOLTIP, "The unit(s) that will cause the selected widget(s) to fade in whenever any of their powers match the specified condition")
    KongConfig_PowerUnitsComboBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_PowerUnitsComboBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_PowerUnitsComboBox.pullout.frame:Hide()
    
    
    -- Less than or Greater than
    KongConfig_PowerComparisonComboBox = AceGUI:Create("Dropdown")
    KongConfig_PowerComparisonComboBox:SetWidth(50)
    KongConfig_PowerComparisonComboBox:SetHeight(-48)
    KongConfig_PowerComparisonComboBox:SetList({"<",">"})
    KongConfig_PowerComparisonComboBox:SetUserData(TRIGGER, "power")
    KongConfig_PowerComparisonComboBox:SetCallback("OnValueChanged", KongConfig_PowerComparisonComboBox_OnValueChanged)
    KongConfig_PowerComparisonComboBox:SetUserData(TITLE, "Power Less Than or Greater Than Dropdown")
    KongConfig_PowerComparisonComboBox:SetUserData(TOOLTIP, "Determines if the selected widget(s) fade in when power is above or below the specified amount")
    KongConfig_PowerComparisonComboBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_PowerComparisonComboBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_PowerComparisonComboBox.pullout.frame:Hide()
    KongConfig_PowerComparisonComboBox.pullout:SetCallback("OnOpen", function(self)
		self.open = true
    end)
    
    -- Power Threshold
    KongConfig_PowerThresholdSlider = AceGUI:Create("Slider")
    KongConfig_PowerThresholdSlider:SetWidth(COLUMN_WIDTH)
    KongConfig_PowerThresholdSlider:SetIsPercent(true)
    KongConfig_PowerThresholdSlider:SetSliderValues(0, 1, .01)
    KongConfig_PowerThresholdSlider:SetUserData(TRIGGER, "power")
    KongConfig_PowerThresholdSlider:SetUserData(FIELD, "threshold")
    KongConfig_PowerThresholdSlider:SetCallback("OnMouseUp", KongConfig_PowerThresholdSlider_OnMouseUp)
    KongConfig_PowerThresholdSlider:SetUserData(TITLE, "Power Threshold")
    KongConfig_PowerThresholdSlider:SetUserData(TOOLTIP, "The amount of power which will cause the selected widget(s) to fade in")
    KongConfig_PowerThresholdSlider:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_PowerThresholdSlider:SetCallback("OnLeave", KongConfig_UpdateTooltip)
     
    -- Settings Group
    KongConfig_PowerSettingsGroup = AceGUI:Create("SimpleGroup")
    KongConfig_PowerSettingsGroup:SetWidth(COLUMN_WIDTH)
    KongConfig_PowerSettingsGroup:SetLayout("Flow")
    KongConfig_PowerSettingsGroup:AddChild(KongConfig_PowerUnitsComboBox)
    KongConfig_PowerSettingsGroup:AddChild(KongConfig_PowerComparisonComboBox)
    KongConfig_PowerSettingsGroup:AddChild(KongConfig_PowerThresholdSlider)
     
    KongConfig_PowerShowCheckBox:SetUserData(OWNER, KongConfig_PowerSettingsGroup.frame)
    KongConfig_PowerTypesComboBox:SetUserData(OWNER, KongConfig_PowerSettingsGroup.frame)
    KongConfig_PowerUnitsComboBox:SetUserData(OWNER, KongConfig_PowerSettingsGroup.frame)
    KongConfig_PowerComparisonComboBox:SetUserData(OWNER, KongConfig_PowerSettingsGroup.frame)
    KongConfig_PowerThresholdSlider:SetUserData(OWNER, KongConfig_PowerSettingsGroup.frame)
    
    -- Power Alpha
    KongConfig_PowerAlphaCheckBox, KongConfig_PowerAlphaSlider, KongConfig_PowerAlphaGroup =
        KongConfig_CreateTriggerSliderGroup(SHOWN_ALPHA, "power", "alphaIn",
        "The transparency of the selected widget(s) while the given power condition is met")
    KongConfig_PowerAlphaSlider:SetIsPercent(true)
    KongConfig_PowerAlphaSlider:SetSliderValues(0, 1, .01)
      
    -- Power Fade In
    KongConfig_PowerFadeInCheckBox, KongConfig_PowerFadeInTimeSlider, KongConfig_PowerFadeInGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_IN_TIME, "power", "secondsIn",
        "The duration over which to fade in the selected widget(s) when the given power condition is met")
    KongConfig_PowerFadeInTimeSlider:SetSliderValues(0, 10, .1)

    -- Power Fade Out
    KongConfig_PowerFadeOutCheckBox, KongConfig_PowerFadeOutTimeSlider, KongConfig_PowerFadeOutGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_OUT_TIME, "power", "secondsOut",
        "The duration over which to fade out the selected widget(s) when the given power condition is no longer met")
    KongConfig_PowerFadeOutTimeSlider:SetSliderValues(0, 10, .1)
    
    KongConfig_PowerGroup:AddChild(KongConfig_PowerShowCheckBox)
    KongConfig_PowerGroup:AddChild(KongConfig_PowerTypesComboBox)
    KongConfig_PowerGroup:AddChild(KongConfig_PowerOfLabel)
    KongConfig_PowerGroup:AddChild(KongConfig_PowerSettingsGroup)
    KongConfig_PowerGroup:AddChild(KongConfig_PowerAlphaGroup)
    KongConfig_PowerGroup:AddChild(KongConfig_PowerFadeInGroup)
    KongConfig_PowerGroup:AddChild(KongConfig_PowerFadeOutGroup)
end

function KongConfig_InitCastingComponents()

    KongConfig_CastingGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_CastingGroup:SetRelativeWidth(1)
    KongConfig_CastingGroup:SetLayout("Flow")
    KongConfig_CastingGroup:SetText("Casting")
       
    -- Casting CheckBoxes
    KongConfig_CastingShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_CastingShowCheckBox:SetLabel("Show when Casting")
    KongConfig_CastingShowCheckBox:SetCallback("OnValueChanged", KongConfig_ShowBooleanRadioButton_OnValueChanged)
    KongConfig_CastingShowCheckBox:SetUserData(TRIGGER, "casting")
    KongConfig_CastingShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) while casting")
    KongConfig_CastingShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_CastingShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_CastingShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    KongConfig_NocastingShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_NocastingShowCheckBox:SetLabel("Show when not Casting")
    KongConfig_NocastingShowCheckBox:SetCallback("OnValueChanged", KongConfig_ShowBooleanRadioButton_OnValueChanged)
    KongConfig_NocastingShowCheckBox:SetUserData(TRIGGER, "nocasting")
    KongConfig_NocastingShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) while not casting")
    KongConfig_NocastingShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_NocastingShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_NocastingShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    KongConfig_CastingRadioButtonGroup = AceGUI:Create("SimpleGroup")
    KongConfig_CastingRadioButtonGroup:SetWidth(COLUMN_WIDTH)
    KongConfig_CastingRadioButtonGroup:SetLayout("Flow")
    KongConfig_CastingRadioButtonGroup:AddChild(KongConfig_CastingShowCheckBox)
    KongConfig_CastingRadioButtonGroup:AddChild(KongConfig_NocastingShowCheckBox)
     
    -- Casting Alpha
    KongConfig_CastingAlphaCheckBox, KongConfig_CastingAlphaSlider, KongConfig_CastingAlphaGroup =
        KongConfig_CreateTriggerSliderGroup(SHOWN_ALPHA, "casting", "alphaIn",
        "The transparency of the selected widget(s) while casting",
        "The transparency of the selected widget(s) while not casting")
    KongConfig_CastingAlphaSlider:SetIsPercent(true)
    KongConfig_CastingAlphaSlider:SetSliderValues(0, 1, .01)
      
    -- Casting Fade In
    KongConfig_CastingFadeInCheckBox, KongConfig_CastingFadeInTimeSlider, KongConfig_CastingFadeInGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_IN_TIME, "casting", "secondsIn",
        "The duration over which to fade in the selected widget(s) when casting starts",
        "The duration over which to fade in the selected widget(s) when casting stops")
    KongConfig_CastingFadeInTimeSlider:SetSliderValues(0, 10, .1)

    -- Casting Fade Out
    KongConfig_CastingFadeOutCheckBox, KongConfig_CastingFadeOutTimeSlider, KongConfig_CastingFadeOutGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_OUT_TIME, "casting", "secondsOut",
        "The duration over which to fade out the selected widget(s) when casting stops",
        "The duration over which to fade out the selected widget(s) when casting starts")
    KongConfig_CastingFadeOutTimeSlider:SetSliderValues(0, 10, .1)
    
    KongConfig_CastingGroup:AddChild(KongConfig_CastingRadioButtonGroup)
    KongConfig_CastingGroup:AddChild(KongConfig_CastingAlphaGroup)
    KongConfig_CastingGroup:AddChild(KongConfig_CastingFadeInGroup)
    KongConfig_CastingGroup:AddChild(KongConfig_CastingFadeOutGroup)
end

function KongConfig_InitMacroComponents()

    KongConfig_MacroGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_MacroGroup:SetLayout("Flow")
    KongConfig_MacroGroup:SetFullWidth(true)
    KongConfig_MacroGroup:SetText("Macro")
    
    -- Macro Condition
    KongConfig_MacroShowCheckBox = AceGUI:Create("CheckBox")
    KongConfig_MacroShowCheckBox:SetLabel("Macro Condition")
    KongConfig_MacroShowCheckBox:SetHeight(15)
    KongConfig_MacroShowCheckBox:SetFullWidth(true)
    KongConfig_MacroShowCheckBox:SetUserData(TRIGGER, "macro")
    KongConfig_MacroShowCheckBox:SetUserData(FIELD, field)
    KongConfig_MacroShowCheckBox:SetCallback("OnValueChanged", KongConfig_MacroShowCheckBox_OnValueChanged)
    KongConfig_MacroShowCheckBox:SetUserData(TOOLTIP, "Show the selected widget(s) while a user-specified macro condition is true. [Square brackets] are required.")
    KongConfig_MacroShowCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_MacroShowCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_MacroShowCheckBox.ToggleChecked = KongConfig_ToggleChecked
    KongConfig_MacroShowCheckBox.frame:SetHitRectInsets(0,0,0,-28)
   
    KongConfig_MacroEditBox = AceGUI:Create("EditBox")
    KongConfig_MacroEditBox:SetFullWidth(true)
    KongConfig_MacroEditBox:SetCallback("OnEnterPressed", KongConfig_MacroEditBox_OnEnterPressed)
    KongConfig_MacroEditBox:SetUserData(TITLE, "Macro Condition")
    KongConfig_MacroEditBox:SetUserData(TOOLTIP, "Show the selected widget(s) while a user-specified macro condition is true. [Square brackets] are required.")
    KongConfig_MacroEditBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_MacroEditBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    
    KongConfig_MacroConditionGroup = AceGUI:Create("SimpleGroup")
    KongConfig_MacroConditionGroup:SetWidth(COLUMN_WIDTH)
    KongConfig_MacroConditionGroup:SetLayout("Flow")
    KongConfig_MacroConditionGroup:AddChild(KongConfig_MacroShowCheckBox)
    KongConfig_MacroConditionGroup:AddChild(KongConfig_MacroEditBox)
     
    KongConfig_MacroShowCheckBox:SetUserData(OWNER, KongConfig_MacroConditionGroup.frame)
    KongConfig_MacroEditBox:SetUserData(OWNER, KongConfig_MacroConditionGroup.frame)
    
    -- Macro Alpha
    KongConfig_MacroAlphaCheckBox, KongConfig_MacroAlphaSlider, KongConfig_MacroAlphaGroup =
        KongConfig_CreateTriggerSliderGroup(SHOWN_ALPHA, "macro", "alphaIn",
        "The transparency of the selected widget(s) while the given condition is true")
    KongConfig_MacroAlphaSlider:SetIsPercent(true)
    KongConfig_MacroAlphaSlider:SetSliderValues(0, 1, .01)
      
    -- Macro Fade In
    KongConfig_MacroFadeInCheckBox, KongConfig_MacroFadeInTimeSlider, KongConfig_MacroFadeInGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_IN_TIME, "macro", "secondsIn",
        "The duration over which to fade in the selected widget(s) when the given condition becomes true")
    KongConfig_MacroFadeInTimeSlider:SetSliderValues(0, 10, .1)

    -- Macro Fade Out
    KongConfig_MacroFadeOutCheckBox, KongConfig_MacroFadeOutTimeSlider, KongConfig_MacroFadeOutGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_OUT_TIME, "macro", "secondsOut",
        "The duration over which to fade out the selected widget(s) when the given condition becomes false")
    KongConfig_MacroFadeOutTimeSlider:SetSliderValues(0, 10, .1)
    
    KongConfig_MacroGroup:AddChild(KongConfig_MacroConditionGroup)
    KongConfig_MacroGroup:AddChild(KongConfig_MacroAlphaGroup)
    KongConfig_MacroGroup:AddChild(KongConfig_MacroFadeInGroup)
    KongConfig_MacroGroup:AddChild(KongConfig_MacroFadeOutGroup)
end

function KongConfig_InitMouseoverComponents()

    KongConfig_MouseoverGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_MouseoverGroup:SetLayout("Flow")
    KongConfig_MouseoverGroup:SetFullWidth(true)
    KongConfig_MouseoverGroup:SetText("Mouseover")
    
    KongConfig_MouseoverLabelPanel = AceGUI:Create("Label")
    KongConfig_MouseoverLabelPanel:SetText("Mouseover fading is always\nenabled for registered frames.")
    KongConfig_MouseoverLabelPanel:SetWidth(COLUMN_WIDTH)
    
    -- Mouseover Alpha
    KongConfig_MouseoverAlphaCheckBox, KongConfig_MouseoverAlphaSlider, KongConfig_MouseoverAlphaGroup =
        KongConfig_CreateTriggerSliderGroup(SHOWN_ALPHA, "mouseover", "alphaIn",
        "The transparency of the selected widget(s) while the cursor is over them")
    KongConfig_MouseoverAlphaSlider:SetIsPercent(true)
    KongConfig_MouseoverAlphaSlider:SetSliderValues(0, 1, .01)
      
    -- Mouseover Fade In
    KongConfig_MouseoverFadeInCheckBox, KongConfig_MouseoverFadeInTimeSlider, KongConfig_MouseoverFadeInGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_IN_TIME, "mouseover", "secondsIn",
        "The duration over which to fade in the selected widget(s) when the cursor moves over them")
    KongConfig_MouseoverFadeInTimeSlider:SetSliderValues(0, 10, .1)

    -- Mouseover Fade Out
    KongConfig_MouseoverFadeOutCheckBox, KongConfig_MouseoverFadeOutTimeSlider, KongConfig_MouseoverFadeOutGroup =
        KongConfig_CreateTriggerSliderGroup(FADE_OUT_TIME, "mouseover", "secondsOut",
        "The duration over which to fade out the selected widget(s) when the cursor leaves")
    KongConfig_MouseoverFadeOutTimeSlider:SetSliderValues(0, 10, .1)
    
    KongConfig_MouseoverGroup:AddChild(KongConfig_MouseoverLabelPanel)
    KongConfig_MouseoverGroup:AddChild(KongConfig_MouseoverAlphaGroup)
    KongConfig_MouseoverGroup:AddChild(KongConfig_MouseoverFadeInGroup)
    KongConfig_MouseoverGroup:AddChild(KongConfig_MouseoverFadeOutGroup)
end

function KongConfig_InitMouseoverGroupComponents()

    KongConfig_MouseoverGroupsGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_MouseoverGroupsGroup:SetLayout("Flow")
    KongConfig_MouseoverGroupsGroup:SetFullWidth(true)
    KongConfig_MouseoverGroupsGroup:SetText("Mouseover Grouping")
    
    KongConfig_GroupsComboBox = AceGUI:Create("Dropdown")
    KongConfig_GroupsComboBox:SetWidth(COLUMN_WIDTH)
    KongConfig_GroupsComboBox:SetLabel("Mouseover Groups")
    KongConfig_GroupsComboBox:SetMultiselect(true)
    KongConfig_GroupsComboBox:SetCallback("OnValueChanged", KongConfig_GroupsComboBox_OnValueChanged)
    KongConfig_GroupsComboBox:SetUserData(TITLE, "Mouseover Groups Selection")
    KongConfig_GroupsComboBox:SetUserData(TOOLTIP, "Lists the available mouseover groups. When the cursor enters any member of a mouseover group, all members of that group are shown. Groups that the selected widget(s) are part of are checked.")
    KongConfig_GroupsComboBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_GroupsComboBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_GroupsComboBox.pullout.frame:Hide()
    
    KongConfig_NewGroupEditBox = AceGUI:Create("EditBox")
    KongConfig_NewGroupEditBox:SetWidth(COLUMN_WIDTH)
    KongConfig_NewGroupEditBox:SetLabel("New Group:")
    KongConfig_NewGroupEditBox:SetCallback("OnEnterPressed", KongConfig_NewGroupEditBox_OnEnterPressed)
    KongConfig_NewGroupEditBox:SetUserData(TITLE, "New Group Field")
    KongConfig_NewGroupEditBox:SetUserData(TOOLTIP, "Adds the selected widget(s) to a new group with a given name.")
    KongConfig_NewGroupEditBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_NewGroupEditBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    
    KongConfig_MouseoverGroupsGroup:AddChild(KongConfig_GroupsComboBox)
    KongConfig_MouseoverGroupsGroup:AddChild(KongConfig_NewGroupEditBox)
end

function KongConfig_InitAdvancedComponents()

    KongConfig_AdvancedGroup = AceGUI:Create("CollapsibleGroup")
    KongConfig_AdvancedGroup:SetLayout("Flow")
    KongConfig_AdvancedGroup:SetFullWidth(true)
    KongConfig_AdvancedGroup:SetText("Advanced")
    
    KongConfig_OverrideAlphaCheckBox = AceGUI:Create("CheckBox")
    KongConfig_OverrideAlphaCheckBox:SetWidth(COLUMN_WIDTH)
    KongConfig_OverrideAlphaCheckBox:SetLabel("Override Alpha")
    KongConfig_OverrideAlphaCheckBox:SetCallback("OnValueChanged", KongConfig_OverrideAlphaCheckBox_OnValueChanged)
    KongConfig_OverrideAlphaCheckBox:SetUserData(TOOLTIP, "Prevents the selected widget(s) from fading back in by themselves when faded out by Kong. Use this for widgets that change their own alphas (i.e. they \"flicker\" or \"appear for no reason\").")
    KongConfig_OverrideAlphaCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_OverrideAlphaCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_OverrideAlphaCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    KongConfig_DisableDrawCheckBox = AceGUI:Create("CheckBox")
    KongConfig_DisableDrawCheckBox:SetWidth(COLUMN_WIDTH)
    KongConfig_DisableDrawCheckBox:SetLabel("Don't Draw if Hidden")
    KongConfig_DisableDrawCheckBox:SetCallback("OnValueChanged", KongConfig_DisableDrawCheckBox_OnValueChanged)
    KongConfig_DisableDrawCheckBox:SetUserData(TOOLTIP, "Prevents the selected widget(s) from drawing themselves while hidden. Only use this for widgets that have parts that do not fade out.")
    KongConfig_DisableDrawCheckBox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_DisableDrawCheckBox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_DisableDrawCheckBox.ToggleChecked = KongConfig_ToggleChecked
    
    KongConfig_PersistAsDropDown = AceGUI:Create("Dropdown")
    KongConfig_PersistAsDropDown:SetFullWidth(true)
    KongConfig_PersistAsDropDown:SetLabel("Save As")
    KongConfig_PersistAsDropDown:SetCallback("OnValueChanged", KongConfig_PersistAsComboBox_OnValueChanged)
    KongConfig_PersistAsDropDown:SetUserData(TITLE, "Save As Selection")
    KongConfig_PersistAsDropDown:SetUserData(TOOLTIP, "The \"name\" with which Kong saves settings associated with the selected widget. Kong will use this name to find the widget again at the next login or /reload, so try to pick something that will be there every session.")
    KongConfig_PersistAsDropDown:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    KongConfig_PersistAsDropDown:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    KongConfig_PersistAsDropDown:SetList({""})
    KongConfig_PersistAsDropDown.button:HookScript("OnClick", KongConfig_PersistAsDropDown_OnClick);
    KongConfig_PersistAsDropDown.pullout.frame:Hide()
    
    KongConfig_AdvancedGroup:AddChild(KongConfig_OverrideAlphaCheckBox)
    KongConfig_AdvancedGroup:AddChild(KongConfig_DisableDrawCheckBox)
    KongConfig_AdvancedGroup:AddChild(KongConfig_PersistAsDropDown)
end
  
function KongConfig_CreateTriggerSliderGroup(text, trigger, field, tooltipTrigger, tooltipNotrigger)

    local checkbox = AceGUI:Create("CheckBox")
    checkbox:SetLabel(text)
    checkbox:SetHeight(0)
    checkbox:SetUserData(TRIGGER, trigger)
    checkbox:SetUserData(FIELD, field)
    checkbox:SetUserData(TITLE, text)
    checkbox:SetUserData(TOOLTIP..trigger, tooltipTrigger)
    checkbox:SetUserData(TOOLTIP.."no"..trigger, tooltipNotrigger)
    checkbox:SetCallback("OnValueChanged", KongConfig_SliderCheckBox_OnValueChanged)
    checkbox:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    checkbox:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    checkbox.ToggleChecked = KongConfig_ToggleChecked
   
    local slider = AceGUI:Create("Slider")
    slider:SetLabel("")
    slider:SetUserData(TRIGGER, trigger)
    slider:SetUserData(FIELD, field)
    slider:SetUserData(TITLE, text)
    slider:SetUserData(TOOLTIP..trigger, tooltipTrigger)
    slider:SetUserData(TOOLTIP.."no"..trigger, tooltipNotrigger)
    slider:SetCallback("OnMouseUp", KongConfig_TriggerSlider_OnMouseUp)
    slider:SetCallback("OnEnter", KongConfig_UpdateTooltip)
    slider:SetCallback("OnLeave", KongConfig_UpdateTooltip)
    slider.slider:SetHitRectInsets(0,0,0,0)

    local group = AceGUI:Create("SimpleGroup")
    group:SetWidth(COLUMN_WIDTH)
    group:SetLayout("Flow")
    group:AddChild(checkbox)
    group:AddChild(slider)
    
    checkbox:SetUserData(OWNER, group.frame)
    slider:SetUserData(OWNER, group.frame)
    
    return checkbox, slider, group
end

function KongConfig_OnClose()
        
    for name, frame in pairs(KongConfig_Frames) do
        frame:Hide()
    end
    
    -- Fade registered frames
    for Root, Kong in pairs(Kong_Frames) do
        if Kong.config then
            Kong_FadeOut(Root, Kong.config)
            Kong.config = nil
        end
    end
    
    -- Restore the original error display
    Kong_Error = Kong_ErrorOriginal
end

function KongConfig_CoverButton_OnMouseWheel(self, dir)

    if (dir == 1) then
        local level = self:GetFrameLevel()
        for name, frame in pairs(KongConfig_Frames) do
            if frame:GetFrameLevel() < level then
                frame:SetFrameLevel(frame:GetFrameLevel() + 1)
            end
        end
        self:SetFrameLevel(0)
    else
        local lowestFrame
        for name, frame in pairs(KongConfig_Frames) do
            if MouseIsOver(frame) then
                if (not lowestFrame) or frame:GetFrameLevel() < lowestFrame:GetFrameLevel() then
                    lowestFrame = frame
                end
            end
        end
        KongConfig_BringToFront(lowestFrame)
    end
    
    -- Make wow re-assign mouse focus
    self:Hide()
    self:Show()
end

function KongConfig_BringToFront(focus)
    local level = focus:GetFrameLevel()
    for name, frame in pairs(KongConfig_Frames) do
        if frame:GetFrameLevel() > level then
            frame:SetFrameLevel(frame:GetFrameLevel() - 1)
        end
    end
    focus:SetFrameLevel(KongConfig_NumFrames-1)
end

function KongConfig_CoverButton_OnClick(self)

    -- Recolor Kong config frames
    if IsControlKeyDown() or IsShiftKeyDown() then
        if KongConfig_SelectedFrames[self] then
            KongConfig_SelectedFrames[self] = nil
        else
            KongConfig_SelectedFrames[self] = self
        end
        KongConfig_CoverButton_Update(self)
    else
        for frame in pairs(KongConfig_SelectedFrames) do
            KongConfig_SelectedFrames[frame] = nil
            KongConfig_CoverButton_Update(frame)
        end
        KongConfig_SelectedFrames[self] = self
        KongConfig_CoverButton_Update(self)
    end

    KongConfig_UpdateComponents() 
    KongConfig_AutoExpandAndCollapse()
    KongConfig_BringToFront(self)
	
    if nil == next(KongConfig_SelectedFrames) then
        KongConfig:SetStatusText("Select a widget to configure.")
    else
        for name, frame in pairs(KongConfig_Frames) do
            if MouseIsOver(frame) and frame ~= self then
                KongConfig:SetStatusText("Use mouse wheel to uncover widgets.")
                return
            end
        end
        if nil == next(KongConfig_SelectedFrames, next(KongConfig_SelectedFrames)) then
            KongConfig:SetStatusText("Shift-click to select multiple widgets.")
        else
            KongConfig:SetStatusText("")
        end
    end
end

function KongConfig_AutoExpandAndCollapse()

    KongConfig_DefaultsGroup:SetCollapsed(KongConfig_FadeCheckBox:GetValue() == false)
    KongConfig_CombatGroup:SetCollapsed((KongConfig_CombatShowCheckBox:GetValue() == false)
        and (KongConfig_NocombatShowCheckBox:GetValue() == false))
    KongConfig_VehicleGroup:SetCollapsed((KongConfig_VehicleShowCheckBox:GetValue() == false) 
        and (KongConfig_NovehicleShowCheckBox:GetValue() == false))
    KongConfig_CastingGroup:SetCollapsed((KongConfig_CastingShowCheckBox:GetValue() == false) 
        and (KongConfig_NocastingShowCheckBox:GetValue() == false))
    KongConfig_HealthGroup:SetCollapsed(KongConfig_HealthShowCheckBox:GetValue() == false)
    KongConfig_PowerGroup:SetCollapsed(KongConfig_PowerShowCheckBox:GetValue() == false)
    KongConfig_MacroGroup:SetCollapsed(KongConfig_MacroShowCheckBox:GetValue() == false)
    KongConfig_MouseoverGroup:SetCollapsed(KongConfig_FadeCheckBox:GetValue() == false)
    
    local hasGroups = false
    local hasAdvancedSettings = false
    -- if KongConfig_FadeCheckBox:GetValue() then
        for _, SelectedFrame in pairs(KongConfig_SelectedFrames) do
            if Kong_Frames[SelectedFrame.uiFrame] then
                for name in pairs(Kong_Settings.Groups) do 
                    if Kong_Settings.Groups[name][Kong_Frames[SelectedFrame.uiFrame].index] then
                        hasGroups = true
                        break
                    end
                end
                if Kong_Frames[SelectedFrame.uiFrame].overrideAlpha 
                or Kong_Frames[SelectedFrame.uiFrame].disableDrawWhenHidden 
                or type(Kong_Frames[SelectedFrame.uiFrame].index) == "table" then 
                    hasAdvancedSettings = true
                end
            end
        end
    -- end
    KongConfig_MouseoverGroupsGroup:SetCollapsed(not hasGroups)
    KongConfig_AdvancedGroup:SetCollapsed(not hasAdvancedSettings)
end

local SelectedBackdrop = CopyTable(COVER_BUTTON_BACKDROP)
function KongConfig_CoverButton_Update(button)
    
    if KongConfig_SelectedFrames[button] then
        button:SetBackdrop(SelectedBackdrop)
        button:SetBackdropColor(unpack(COLOR_SELECTED))
        button:SetBackdropBorderColor(unpack(COLOR_BORDER_SELECTED))
        button:LockHighlight()
        _G[button:GetName().."Title"]:SetTextColor(1, 1, 0, 1)
    else
        button:SetBackdrop(COVER_BUTTON_BACKDROP)
        if Kong_Frames[button.uiFrame] then 
            button:SetBackdropColor(unpack(COLOR_REGISTERED))
        else
            button:SetBackdropColor(unpack(COLOR_UNREGISTERED))
        end
        button:SetBackdropBorderColor(unpack(COLOR_BORDER_DESELECTED))
        button:GetHighlightTexture():SetVertexColor(1, 1, 1, 1)
        button:UnlockHighlight()
        _G[button:GetName().."Title"]:SetTextColor(1, 1, 1, 1)
    end
end
       
local SELECTION_BLINK_PERIOD = 1;
local updateTimer = 0;
function KongConfig_OnUpdate(self, elapsed)
    
    updateTimer = updateTimer - elapsed;
    if updateTimer <= 0 then
        updateTimer = SELECTION_BLINK_PERIOD;
    end
    
    local numSelected = 0;
    SelectedBackdrop.edgeSize = 1 + math.abs(4*(updateTimer/SELECTION_BLINK_PERIOD)-2)
    for Frame in pairs(KongConfig_SelectedFrames) do
        KongConfig_CoverButton_Update(Frame)
        Frame:GetHighlightTexture():SetVertexColor(1, 1, 1, math.abs(2*(updateTimer/SELECTION_BLINK_PERIOD)-1))
        numSelected = numSelected + 1
    end
    
    local showTip
    local Focus = GetMouseFocus()
    local numUnderCursor = 0
    for name, Frame in pairs(KongConfig_Frames) do 
        showTip = (Frame == Focus)
        if MouseIsOver(Frame) then
            numUnderCursor = numUnderCursor + 1
        end
    end
    local unselectedUnderCursor = not KongConfig_SelectedFrames[Focus]

    if showTip then
        GameTooltip:SetOwner(KongConfig.frame, "ANCHOR_CURSOR")
        if (numUnderCursor > 0) and numSelected == 0 then
            GameTooltip:AddLine("Click to configure.")
        elseif (numUnderCursor > 0) and unselectedUnderCursor then
            GameTooltip:AddLine("Shift-click to select multiple widgets.")
        elseif numUnderCursor > 1 then
            GameTooltip:AddLine("Use the mouse wheel to uncover widgets.")
        end
    elseif GameTooltip:IsOwned(KongConfig.frame) then
        GameTooltip:Hide()
    end
    
    if KongConfig_PersistAsCoroutine
    and coroutine.status(KongConfig_PersistAsCoroutine) == "suspended" then
        local status, err = coroutine.resume(KongConfig_PersistAsCoroutine)
        if not status then
            error(err)
        end
    end
end

local MAX_DEPTH = 4
function KongConfig_RecursiveFrameSearch(Frame, tbl, depth, path)
       
    for name, value in pairs(tbl) do
        if (type(name) == "string") or (type(name) == "number") or (type(name) == "boolean") then
            if (type(value) == "table") and (value ~= tbl) then
                table.insert(path, name)
                if Frame == value then
                    if (string.sub(path[1], 1, 4) ~= "Kong") and (string.sub(path[1], 1, 6) ~= "AceGUI") then
                        local code = "";
                        for i = 1,#path do
                            if type(path[i]) == "string" then
                                code = code .. "[\"" .. path[i] .. "\"]"
                            else
                                code = code .. "[" .. tostring(path[i]) .. "]"
                            end
                        end
                        KongConfig_PersistAsDropDown:AddItem(code, Debracket(code))
                    end
                elseif depth <= MAX_DEPTH then
                    KongConfig_RecursiveFrameSearch(Frame, value, depth+1, path)
                end
                table.remove(path)
            end
        end
    end
end

function KongConfig_PersistableFramePathSearch(frame)
    KongConfig_RecursiveFrameSearch(frame, _G, 1, {})
    
    KongConfig_UpdatePersistAsPullout(KongConfig_PersistAsDropDown.pullout);
    coroutine.yield()
    for _, child in pairs({frame:GetChildren()}) do
       KongConfig_PersistableFramePathSearch(child)
    end
end

function KongConfig_UpdatePersistAsPullout(pullout)
    local items = pullout.items
    local frame = pullout.frame
    local itemFrame = pullout.itemFrame
    
    local height = 8
    for i, item in pairs(items) do
        if i == 1 then
            item:SetPoint("TOP", itemFrame, "TOP", 0, -2)
        else
            item:SetPoint("TOP", items[i-1].frame, "BOTTOM", 0, 1)
        end
        
        item:Show()
        
        if item:GetText() == KongConfig_PersistAsDropDown.text:GetText() then
            item.check:Show();
        end
        
        height = height + 16
    end
    itemFrame:SetHeight(height)
end

function KongConfig_UpdateComponents()

    KongConfig_UpdateCheckboxes()

    KongConfig_UpdateMacro()
    
    KongConfig_UpdateSliders()
    
    KongConfig_UpdatePower("health", KongConfig_HealthShowCheckBox, KongConfig_HealthUnitsComboBox, KongConfig_HealthComparisonComboBox)
    
    KongConfig_UpdatePower("power", KongConfig_HealthShowCheckBox, KongConfig_PowerUnitsComboBox, KongConfig_PowerComparisonComboBox)
    
    KongConfig_UpdateGroups()
    
    KongConfig_UpdateAdvanced()
    
    KongConfig_EnableComponents()
end

function KongConfig_UpdateCheckboxes()

    -- Set the checkbox state based on selected frames
    KongConfig_FadeCheckBox:SetUserData(true, nil)
    KongConfig_FadeCheckBox:SetUserData(false, nil)
    
    KongConfig_HiddenAlphaCheckBox:SetUserData(true, nil)
    KongConfig_HiddenAlphaCheckBox:SetUserData(false, nil)
    KongConfig_ShownAlphaCheckBox:SetUserData(true, nil)
    KongConfig_ShownAlphaCheckBox:SetUserData(false, nil)
    KongConfig_FadeInCheckBox:SetUserData(true, nil)
    KongConfig_FadeInCheckBox:SetUserData(false, nil)
    KongConfig_FadeOutCheckBox:SetUserData(true, nil)
    KongConfig_FadeOutCheckBox:SetUserData(false, nil)
    
    KongConfig_CombatShowCheckBox:SetUserData(true, nil)
    KongConfig_CombatShowCheckBox:SetUserData(false, nil)
    KongConfig_NocombatShowCheckBox:SetUserData(true, nil)
    KongConfig_NocombatShowCheckBox:SetUserData(false, nil)
    
    KongConfig_CombatAlphaCheckBox:SetUserData(true, nil)
    KongConfig_CombatAlphaCheckBox:SetUserData(false, nil)
    KongConfig_CombatFadeInCheckBox:SetUserData(true, nil)
    KongConfig_CombatFadeInCheckBox:SetUserData(false, nil)
    KongConfig_CombatFadeOutCheckBox:SetUserData(true, nil)
    KongConfig_CombatFadeOutCheckBox:SetUserData(false, nil)
    
    KongConfig_VehicleShowCheckBox:SetUserData(true, nil)
    KongConfig_VehicleShowCheckBox:SetUserData(false, nil)
    KongConfig_NovehicleShowCheckBox:SetUserData(true, nil)
    KongConfig_NovehicleShowCheckBox:SetUserData(false, nil)
    
    KongConfig_VehicleAlphaCheckBox:SetUserData(true, nil)
    KongConfig_VehicleAlphaCheckBox:SetUserData(false, nil)
    KongConfig_VehicleFadeInCheckBox:SetUserData(true, nil)
    KongConfig_VehicleFadeInCheckBox:SetUserData(false, nil)
    KongConfig_VehicleFadeOutCheckBox:SetUserData(true, nil)
    KongConfig_VehicleFadeOutCheckBox:SetUserData(false, nil)
    
    KongConfig_CastingShowCheckBox:SetUserData(true, nil)
    KongConfig_CastingShowCheckBox:SetUserData(false, nil)
    KongConfig_NocastingShowCheckBox:SetUserData(true, nil)
    KongConfig_NocastingShowCheckBox:SetUserData(false, nil)
    
    KongConfig_CastingAlphaCheckBox:SetUserData(true, nil)
    KongConfig_CastingAlphaCheckBox:SetUserData(false, nil)
    KongConfig_CastingFadeInCheckBox:SetUserData(true, nil)
    KongConfig_CastingFadeInCheckBox:SetUserData(false, nil)
    KongConfig_CastingFadeOutCheckBox:SetUserData(true, nil)
    KongConfig_CastingFadeOutCheckBox:SetUserData(false, nil)
    
    KongConfig_HealthShowCheckBox:SetUserData(true, nil)
    KongConfig_HealthShowCheckBox:SetUserData(false, nil)
    KongConfig_HealthAlphaCheckBox:SetUserData(true, nil)
    KongConfig_HealthAlphaCheckBox:SetUserData(false, nil)
    KongConfig_HealthFadeInCheckBox:SetUserData(true, nil)
    KongConfig_HealthFadeInCheckBox:SetUserData(false, nil)
    KongConfig_HealthFadeOutCheckBox:SetUserData(true, nil)
    KongConfig_HealthFadeOutCheckBox:SetUserData(false, nil)
    
    KongConfig_PowerShowCheckBox:SetUserData(true, nil)
    KongConfig_PowerShowCheckBox:SetUserData(false, nil)
    KongConfig_PowerAlphaCheckBox:SetUserData(true, nil)
    KongConfig_PowerAlphaCheckBox:SetUserData(false, nil)
    KongConfig_PowerFadeInCheckBox:SetUserData(true, nil)
    KongConfig_PowerFadeInCheckBox:SetUserData(false, nil)
    KongConfig_PowerFadeOutCheckBox:SetUserData(true, nil)
    KongConfig_PowerFadeOutCheckBox:SetUserData(false, nil)
    
    KongConfig_MacroShowCheckBox:SetUserData(true, nil)
    KongConfig_MacroShowCheckBox:SetUserData(false, nil)
    KongConfig_MacroAlphaCheckBox:SetUserData(true, nil)
    KongConfig_MacroAlphaCheckBox:SetUserData(false, nil)
    KongConfig_MacroFadeInCheckBox:SetUserData(true, nil)
    KongConfig_MacroFadeInCheckBox:SetUserData(false, nil)
    KongConfig_MacroFadeOutCheckBox:SetUserData(true, nil)
    KongConfig_MacroFadeOutCheckBox:SetUserData(false, nil)
    
    KongConfig_MouseoverAlphaCheckBox:SetUserData(true, nil)
    KongConfig_MouseoverAlphaCheckBox:SetUserData(false, nil)
    KongConfig_MouseoverFadeInCheckBox:SetUserData(true, nil)
    KongConfig_MouseoverFadeInCheckBox:SetUserData(false, nil)
    KongConfig_MouseoverFadeOutCheckBox:SetUserData(true, nil)
    KongConfig_MouseoverFadeOutCheckBox:SetUserData(false, nil)
    
    KongConfig_OverrideAlphaCheckBox:SetUserData(true, nil)
    KongConfig_OverrideAlphaCheckBox:SetUserData(false, nil)
    
    KongConfig_DisableDrawCheckBox:SetUserData(true, nil)
    KongConfig_DisableDrawCheckBox:SetUserData(false, nil)
    
    for _, SelectedFrame in pairs(KongConfig_SelectedFrames) do
        
        if Kong_Frames[SelectedFrame.uiFrame] then
            KongConfig_FadeCheckBox:SetUserData(true, true)
            
            local triggerDefaults = Kong_Frames[SelectedFrame.uiFrame].TriggerDefaults
            KongConfig_HiddenAlphaCheckBox:SetUserData(nil ~= rawget(triggerDefaults, "alphaOut"), true)
            KongConfig_ShownAlphaCheckBox:SetUserData(nil ~= rawget(triggerDefaults, "alphaIn"), true)
            KongConfig_FadeInCheckBox:SetUserData(nil ~= rawget(triggerDefaults, "secondsIn"), true)
            KongConfig_FadeOutCheckBox:SetUserData(nil ~= rawget(triggerDefaults, "secondsOut"), true)
                
            -- Populate combat group depending on combat/nocombat
            KongConfig_CombatShowCheckBox:SetUserData(nil ~= Kong_Frames[SelectedFrame.uiFrame].combat, true)
            KongConfig_NocombatShowCheckBox:SetUserData(nil ~= Kong_Frames[SelectedFrame.uiFrame].nocombat, true)
            
            local combatTrigger = nil
            if Kong_Frames[SelectedFrame.uiFrame].combat then
                combatTrigger = Kong_Frames[SelectedFrame.uiFrame].combat
            elseif Kong_Frames[SelectedFrame.uiFrame].nocombat then
                combatTrigger = Kong_Frames[SelectedFrame.uiFrame].nocombat
            end
            
            if combatTrigger then
                KongConfig_CombatAlphaCheckBox:SetUserData(nil ~= rawget(combatTrigger, "alphaIn"), true)
                KongConfig_CombatFadeInCheckBox:SetUserData(nil ~= rawget(combatTrigger, "secondsIn"), true)
                KongConfig_CombatFadeOutCheckBox:SetUserData(nil ~= rawget(combatTrigger, "secondsOut"), true)
            end
                
            -- Populate vehicle group depending on vehicle/novehicle
            KongConfig_VehicleShowCheckBox:SetUserData(nil ~= Kong_Frames[SelectedFrame.uiFrame].vehicle, true)
            KongConfig_NovehicleShowCheckBox:SetUserData(nil ~= Kong_Frames[SelectedFrame.uiFrame].novehicle, true)
            
            local vehicleTrigger = nil
            if Kong_Frames[SelectedFrame.uiFrame].vehicle then
                vehicleTrigger = Kong_Frames[SelectedFrame.uiFrame].vehicle
            elseif Kong_Frames[SelectedFrame.uiFrame].novehicle then
                vehicleTrigger = Kong_Frames[SelectedFrame.uiFrame].novehicle
            end
            
            if vehicleTrigger then
                KongConfig_VehicleAlphaCheckBox:SetUserData(nil ~= rawget(vehicleTrigger, "alphaIn"), true)
                KongConfig_VehicleFadeInCheckBox:SetUserData(nil ~= rawget(vehicleTrigger, "secondsIn"), true)
                KongConfig_VehicleFadeOutCheckBox:SetUserData(nil ~= rawget(vehicleTrigger, "secondsOut"), true)
            end
             
            -- Populate casting group depending on casting/nocasting
            KongConfig_CastingShowCheckBox:SetUserData(nil ~= Kong_Frames[SelectedFrame.uiFrame].casting, true)
            KongConfig_NocastingShowCheckBox:SetUserData(nil ~= Kong_Frames[SelectedFrame.uiFrame].nocasting, true)
            
            local castingTrigger = nil
            if Kong_Frames[SelectedFrame.uiFrame].casting then
                castingTrigger = Kong_Frames[SelectedFrame.uiFrame].casting
            elseif Kong_Frames[SelectedFrame.uiFrame].nocasting then
                castingTrigger = Kong_Frames[SelectedFrame.uiFrame].nocasting
            end
            
            if castingTrigger then
                KongConfig_CastingAlphaCheckBox:SetUserData(nil ~= rawget(castingTrigger, "alphaIn"), true)
                KongConfig_CastingFadeInCheckBox:SetUserData(nil ~= rawget(castingTrigger, "secondsIn"), true)
                KongConfig_CastingFadeOutCheckBox:SetUserData(nil ~= rawget(castingTrigger, "secondsOut"), true)
            end
                
            -- Health
            local health = Kong_Frames[SelectedFrame.uiFrame].health
            KongConfig_HealthShowCheckBox:SetUserData(nil ~= health, true)
            if health then
                KongConfig_HealthAlphaCheckBox:SetUserData(nil ~= rawget(health, "alphaIn"), true)
                KongConfig_HealthFadeInCheckBox:SetUserData(nil ~= rawget(health, "secondsIn"), true)
                KongConfig_HealthFadeOutCheckBox:SetUserData(nil ~= rawget(health, "secondsOut"), true)
            end
              
            -- Power
            local power = Kong_Frames[SelectedFrame.uiFrame].power
            KongConfig_PowerShowCheckBox:SetUserData(nil ~= power, true)
            if power then
                KongConfig_PowerAlphaCheckBox:SetUserData(nil ~= rawget(power, "alphaIn"), true)
                KongConfig_PowerFadeInCheckBox:SetUserData(nil ~= rawget(power, "secondsIn"), true)
                KongConfig_PowerFadeOutCheckBox:SetUserData(nil ~= rawget(power, "secondsOut"), true)
            end
            
            -- Macro
            local macro = Kong_Frames[SelectedFrame.uiFrame].macro
            KongConfig_MacroShowCheckBox:SetUserData(nil ~= macro, true)
            if macro then
                KongConfig_MacroAlphaCheckBox:SetUserData(nil ~= rawget(macro, "alphaIn"), true)
                KongConfig_MacroFadeInCheckBox:SetUserData(nil ~= rawget(macro, "secondsIn"), true)
                KongConfig_MacroFadeOutCheckBox:SetUserData(nil ~= rawget(macro, "secondsOut"), true)
            end
            
            -- Mouseover
            local mouseover = Kong_Frames[SelectedFrame.uiFrame].mouseover
            if mouseover then
                KongConfig_MouseoverAlphaCheckBox:SetUserData(nil ~= rawget(mouseover, "alphaIn"), true)
                KongConfig_MouseoverFadeInCheckBox:SetUserData(nil ~= rawget(mouseover, "secondsIn"), true)
                KongConfig_MouseoverFadeOutCheckBox:SetUserData(nil ~= rawget(mouseover, "secondsOut"), true)
            end    
            
            -- Advanced
            KongConfig_OverrideAlphaCheckBox:SetUserData(true == Kong_Frames[SelectedFrame.uiFrame].overrideAlpha, true) 
            KongConfig_DisableDrawCheckBox:SetUserData(true == Kong_Frames[SelectedFrame.uiFrame].disableDrawWhenHidden, true) 
        else
           KongConfig_FadeCheckBox:SetUserData(false, true)
        end
    end
    
    KongConfig_SetCheckBox(KongConfig_FadeCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_HiddenAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_ShownAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_FadeInCheckBox)
    KongConfig_SetCheckBox(KongConfig_FadeOutCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_CombatShowCheckBox)
    KongConfig_SetCheckBox(KongConfig_NocombatShowCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_CombatAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_CombatFadeInCheckBox)
    KongConfig_SetCheckBox(KongConfig_CombatFadeOutCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_VehicleShowCheckBox)
    KongConfig_SetCheckBox(KongConfig_NovehicleShowCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_VehicleAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_VehicleFadeInCheckBox)
    KongConfig_SetCheckBox(KongConfig_VehicleFadeOutCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_CastingShowCheckBox)
    KongConfig_SetCheckBox(KongConfig_NocastingShowCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_CastingAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_CastingFadeInCheckBox)
    KongConfig_SetCheckBox(KongConfig_CastingFadeOutCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_HealthShowCheckBox)
    KongConfig_SetCheckBox(KongConfig_HealthAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_HealthFadeInCheckBox)
    KongConfig_SetCheckBox(KongConfig_HealthFadeOutCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_PowerShowCheckBox)
    KongConfig_SetCheckBox(KongConfig_PowerAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_PowerFadeInCheckBox)
    KongConfig_SetCheckBox(KongConfig_PowerFadeOutCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_MacroShowCheckBox)
    KongConfig_SetCheckBox(KongConfig_MacroAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_MacroFadeInCheckBox)
    KongConfig_SetCheckBox(KongConfig_MacroFadeOutCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_MouseoverAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_MouseoverFadeInCheckBox)
    KongConfig_SetCheckBox(KongConfig_MouseoverFadeOutCheckBox)
    
    KongConfig_SetCheckBox(KongConfig_OverrideAlphaCheckBox)
    KongConfig_SetCheckBox(KongConfig_DisableDrawCheckBox)
end

function KongConfig_EnableComponents()

    local fade = KongConfig_FadeCheckBox:GetValue()
    local combat = KongConfig_CombatShowCheckBox:GetValue() or KongConfig_NocombatShowCheckBox:GetValue()
    local vehicle = KongConfig_VehicleShowCheckBox:GetValue() or KongConfig_NovehicleShowCheckBox:GetValue()
    local casting = KongConfig_CastingShowCheckBox:GetValue() or KongConfig_NocastingShowCheckBox:GetValue()
    local health = KongConfig_HealthShowCheckBox:GetValue()
    local power = KongConfig_PowerShowCheckBox:GetValue()
    local macro = KongConfig_MacroShowCheckBox:GetValue() and (KongConfig_MacroEditBox:GetText() ~= "")
    
    -- Enable/Disable widgets
    KongConfig_FadeCheckBox:SetDisabled(nil == next(KongConfig_SelectedFrames))

    KongConfig_HiddenAlphaCheckBox:SetDisabled(not fade)
    KongConfig_HiddenAlphaSlider:SetDisabled(not (fade and KongConfig_HiddenAlphaCheckBox:GetValue()))
    KongConfig_ShownAlphaCheckBox:SetDisabled(not fade)
    KongConfig_ShownAlphaSlider:SetDisabled(not (fade and KongConfig_ShownAlphaCheckBox:GetValue()))
    KongConfig_FadeInCheckBox:SetDisabled(not fade)
    KongConfig_FadeInSlider:SetDisabled(not (fade and KongConfig_FadeInCheckBox:GetValue()))
    KongConfig_FadeOutCheckBox:SetDisabled(not fade)
    KongConfig_FadeOutSlider:SetDisabled(not (fade and KongConfig_FadeOutCheckBox:GetValue()))
    
    KongConfig_CombatShowCheckBox:SetDisabled(not fade) 
    KongConfig_NocombatShowCheckBox:SetDisabled(not fade) 
    KongConfig_CombatAlphaCheckBox:SetDisabled(not (fade and combat))
    KongConfig_CombatAlphaSlider:SetDisabled(not (fade and combat and KongConfig_CombatAlphaCheckBox:GetValue()))
    KongConfig_CombatFadeInCheckBox:SetDisabled(not (fade and combat))
    KongConfig_CombatFadeInTimeSlider:SetDisabled(not (fade and combat and KongConfig_CombatFadeInCheckBox:GetValue()))
    KongConfig_CombatFadeOutCheckBox:SetDisabled(not (fade and combat))
    KongConfig_CombatFadeOutTimeSlider:SetDisabled(not (fade and combat and KongConfig_CombatFadeOutCheckBox:GetValue()))
    
    KongConfig_VehicleShowCheckBox:SetDisabled(not fade) 
    KongConfig_NovehicleShowCheckBox:SetDisabled(not fade) 
    KongConfig_VehicleAlphaCheckBox:SetDisabled(not (fade and vehicle))
    KongConfig_VehicleAlphaSlider:SetDisabled(not (fade and vehicle and KongConfig_VehicleAlphaCheckBox:GetValue()))
    KongConfig_VehicleFadeInCheckBox:SetDisabled(not (fade and vehicle))
    KongConfig_VehicleFadeInTimeSlider:SetDisabled(not (fade and vehicle and KongConfig_VehicleFadeInCheckBox:GetValue()))
    KongConfig_VehicleFadeOutCheckBox:SetDisabled(not (fade and vehicle))
    KongConfig_VehicleFadeOutTimeSlider:SetDisabled(not (fade and vehicle and KongConfig_VehicleFadeOutCheckBox:GetValue()))
    
    KongConfig_CastingShowCheckBox:SetDisabled(not fade) 
    KongConfig_NocastingShowCheckBox:SetDisabled(not fade) 
    KongConfig_CastingAlphaCheckBox:SetDisabled(not (fade and casting))
    KongConfig_CastingAlphaSlider:SetDisabled(not (fade and casting and KongConfig_CastingAlphaCheckBox:GetValue()))
    KongConfig_CastingFadeInCheckBox:SetDisabled(not (fade and casting))
    KongConfig_CastingFadeInTimeSlider:SetDisabled(not (fade and casting and KongConfig_CastingFadeInCheckBox:GetValue()))
    KongConfig_CastingFadeOutCheckBox:SetDisabled(not (fade and casting))
    KongConfig_CastingFadeOutTimeSlider:SetDisabled(not (fade and casting and KongConfig_CastingFadeOutCheckBox:GetValue()))
    
    KongConfig_HealthShowCheckBox:SetDisabled(not fade)
    KongConfig_HealthUnitsComboBox:SetDisabled(not (fade and KongConfig_HealthShowCheckBox:GetValue()))
    KongConfig_HealthComparisonComboBox:SetDisabled(not (fade and KongConfig_HealthShowCheckBox:GetValue()))
    KongConfig_HealthThresholdSlider:SetDisabled(not (fade and KongConfig_HealthShowCheckBox:GetValue()))
    KongConfig_HealthAlphaCheckBox:SetDisabled(not (fade and health))
    KongConfig_HealthAlphaSlider:SetDisabled(not (fade and health and KongConfig_HealthAlphaCheckBox:GetValue()))
    KongConfig_HealthFadeInCheckBox:SetDisabled(not (fade and health))
    KongConfig_HealthFadeInTimeSlider:SetDisabled(not (fade and health and KongConfig_HealthFadeInCheckBox:GetValue()))
    KongConfig_HealthFadeOutCheckBox:SetDisabled(not (fade and health))
    KongConfig_HealthFadeOutTimeSlider:SetDisabled(not (fade and health and KongConfig_HealthFadeOutCheckBox:GetValue()))
    
    KongConfig_PowerShowCheckBox:SetDisabled(not fade)
    KongConfig_PowerTypesComboBox:SetDisabled(not (fade and KongConfig_PowerShowCheckBox:GetValue()))
    if fade and KongConfig_PowerShowCheckBox:GetValue() then
        KongConfig_PowerOfLabel:SetColor(1, 1, 1)
    else
        KongConfig_PowerOfLabel:SetColor(.5, .5, .5)
    end
    KongConfig_PowerUnitsComboBox:SetDisabled(not (fade and KongConfig_PowerShowCheckBox:GetValue()))
    KongConfig_PowerComparisonComboBox:SetDisabled(not (fade and KongConfig_PowerShowCheckBox:GetValue()))
    KongConfig_PowerThresholdSlider:SetDisabled(not (fade and KongConfig_PowerShowCheckBox:GetValue()))
    KongConfig_PowerAlphaCheckBox:SetDisabled(not (fade and power))
    KongConfig_PowerAlphaSlider:SetDisabled(not (fade and power and KongConfig_PowerAlphaCheckBox:GetValue()))
    KongConfig_PowerFadeInCheckBox:SetDisabled(not (fade and power))
    KongConfig_PowerFadeInTimeSlider:SetDisabled(not (fade and power and KongConfig_PowerFadeInCheckBox:GetValue()))
    KongConfig_PowerFadeOutCheckBox:SetDisabled(not (fade and power))
    KongConfig_PowerFadeOutTimeSlider:SetDisabled(not (fade and power and KongConfig_PowerFadeOutCheckBox:GetValue()))
    
    KongConfig_MacroShowCheckBox:SetDisabled(not fade)
    KongConfig_MacroEditBox:SetDisabled(not (fade and KongConfig_MacroShowCheckBox:GetValue()))
    KongConfig_MacroAlphaCheckBox:SetDisabled(not (fade and macro))
    KongConfig_MacroAlphaSlider:SetDisabled(not (fade and macro and KongConfig_MacroAlphaCheckBox:GetValue()))
    KongConfig_MacroFadeInCheckBox:SetDisabled(not (fade and macro))
    KongConfig_MacroFadeInTimeSlider:SetDisabled(not (fade and macro and KongConfig_MacroFadeInCheckBox:GetValue()))
    KongConfig_MacroFadeOutCheckBox:SetDisabled(not (fade and macro))
    KongConfig_MacroFadeOutTimeSlider:SetDisabled(not (fade and macro and KongConfig_MacroFadeOutCheckBox:GetValue()))
    
    if fade then 
        KongConfig_MouseoverLabelPanel.label:SetTextColor(1,1,1);
    else
        KongConfig_MouseoverLabelPanel.label:SetTextColor(.5,.5,.5);
    end
    KongConfig_MouseoverAlphaCheckBox:SetDisabled(not fade)
    KongConfig_MouseoverAlphaSlider:SetDisabled(not (fade and KongConfig_MouseoverAlphaCheckBox:GetValue()))
    KongConfig_MouseoverFadeInCheckBox:SetDisabled(not fade)
    KongConfig_MouseoverFadeInTimeSlider:SetDisabled(not (fade and KongConfig_MouseoverFadeInCheckBox:GetValue()))
    KongConfig_MouseoverFadeOutCheckBox:SetDisabled(not fade)
    KongConfig_MouseoverFadeOutTimeSlider:SetDisabled(not (fade and KongConfig_MouseoverFadeOutCheckBox:GetValue()))
    
    KongConfig_GroupsComboBox:SetDisabled(not fade)
    KongConfig_NewGroupEditBox:SetDisabled(not fade)
    
    KongConfig_OverrideAlphaCheckBox:SetDisabled(not fade)
    KongConfig_DisableDrawCheckBox:SetDisabled(not fade)
    local selectedFrame = next(KongConfig_SelectedFrames)
    KongConfig_PersistAsDropDown:SetDisabled(not (fade and selectedFrame and not next(KongConfig_SelectedFrames, selectedFrame)))
end

function KongConfig_UpdateSliders()

    -- Slider display
    KongConfig_UpdateTriggerSlider(KongConfig_HiddenAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_ShownAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_FadeInSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_FadeOutSlider)
    
    -- Hidden and Shown alpha are constrained by one another
    if KongConfig_FadeCheckBox:GetValue() then
        KongConfig_ShownAlphaSlider:SetSliderValues(floor(KongConfig_HiddenAlphaSlider:GetValue()*100+.5)/100, 1, .01)
        KongConfig_HiddenAlphaSlider:SetSliderValues(0, floor(KongConfig_ShownAlphaSlider:GetValue()*100+.5)/100, .01)
    end
    
    -- Change the "trigger" user data property depending on combat/nocombat
    if KongConfig_NocombatShowCheckBox:GetValue() then
        KongConfig_CombatAlphaCheckBox:SetUserData(TRIGGER, "nocombat")
        KongConfig_CombatAlphaSlider:SetUserData(TRIGGER, "nocombat")
        KongConfig_CombatFadeInCheckBox:SetUserData(TRIGGER, "nocombat")
        KongConfig_CombatFadeInTimeSlider:SetUserData(TRIGGER, "nocombat")
        KongConfig_CombatFadeOutCheckBox:SetUserData(TRIGGER, "nocombat")
        KongConfig_CombatFadeOutTimeSlider:SetUserData(TRIGGER, "nocombat")
    else
        KongConfig_CombatAlphaCheckBox:SetUserData(TRIGGER, "combat")
        KongConfig_CombatAlphaSlider:SetUserData(TRIGGER, "combat")
        KongConfig_CombatFadeInCheckBox:SetUserData(TRIGGER, "combat")
        KongConfig_CombatFadeInTimeSlider:SetUserData(TRIGGER, "combat")
        KongConfig_CombatFadeOutCheckBox:SetUserData(TRIGGER, "combat")
        KongConfig_CombatFadeOutTimeSlider:SetUserData(TRIGGER, "combat")
    end
    
    KongConfig_UpdateTriggerSlider(KongConfig_CombatAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_CombatFadeInTimeSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_CombatFadeOutTimeSlider)
    
    -- Change the "trigger" user data property depending on vehicle/novehicle
    if KongConfig_NovehicleShowCheckBox:GetValue() then
        KongConfig_VehicleAlphaCheckBox:SetUserData(TRIGGER, "novehicle")
        KongConfig_VehicleAlphaSlider:SetUserData(TRIGGER, "novehicle")
        KongConfig_VehicleFadeInCheckBox:SetUserData(TRIGGER, "novehicle")
        KongConfig_VehicleFadeInTimeSlider:SetUserData(TRIGGER, "novehicle")
        KongConfig_VehicleFadeOutCheckBox:SetUserData(TRIGGER, "novehicle")
        KongConfig_VehicleFadeOutTimeSlider:SetUserData(TRIGGER, "novehicle")
    else
        KongConfig_VehicleAlphaCheckBox:SetUserData(TRIGGER, "vehicle")
        KongConfig_VehicleAlphaSlider:SetUserData(TRIGGER, "vehicle")
        KongConfig_VehicleFadeInCheckBox:SetUserData(TRIGGER, "vehicle")
        KongConfig_VehicleFadeInTimeSlider:SetUserData(TRIGGER, "vehicle")
        KongConfig_VehicleFadeOutCheckBox:SetUserData(TRIGGER, "vehicle")
        KongConfig_VehicleFadeOutTimeSlider:SetUserData(TRIGGER, "vehicle")
    end
    
    KongConfig_UpdateTriggerSlider(KongConfig_VehicleAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_VehicleFadeInTimeSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_VehicleFadeOutTimeSlider)
    
    -- Change the "trigger" user data property depending on casting/nocasting
    if KongConfig_NocastingShowCheckBox:GetValue() then
        KongConfig_CastingAlphaCheckBox:SetUserData(TRIGGER, "nocasting")
        KongConfig_CastingAlphaSlider:SetUserData(TRIGGER, "nocasting")
        KongConfig_CastingFadeInCheckBox:SetUserData(TRIGGER, "nocasting")
        KongConfig_CastingFadeInTimeSlider:SetUserData(TRIGGER, "nocasting")
        KongConfig_CastingFadeOutCheckBox:SetUserData(TRIGGER, "nocasting")
        KongConfig_CastingFadeOutTimeSlider:SetUserData(TRIGGER, "nocasting")
    else
        KongConfig_CastingAlphaCheckBox:SetUserData(TRIGGER, "casting")
        KongConfig_CastingAlphaSlider:SetUserData(TRIGGER, "casting")
        KongConfig_CastingFadeInCheckBox:SetUserData(TRIGGER, "casting")
        KongConfig_CastingFadeInTimeSlider:SetUserData(TRIGGER, "casting")
        KongConfig_CastingFadeOutCheckBox:SetUserData(TRIGGER, "casting")
        KongConfig_CastingFadeOutTimeSlider:SetUserData(TRIGGER, "casting")
    end
    
    KongConfig_UpdateTriggerSlider(KongConfig_CastingAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_CastingFadeInTimeSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_CastingFadeOutTimeSlider)
    
    KongConfig_UpdateTriggerSlider(KongConfig_HealthThresholdSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_HealthAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_HealthFadeInTimeSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_HealthFadeOutTimeSlider)
    
    KongConfig_UpdateTriggerSlider(KongConfig_PowerThresholdSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_PowerAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_PowerFadeInTimeSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_PowerFadeOutTimeSlider)
    
    KongConfig_UpdateTriggerSlider(KongConfig_MacroAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_MacroFadeInTimeSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_MacroFadeOutTimeSlider)
    
    KongConfig_UpdateTriggerSlider(KongConfig_MouseoverAlphaSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_MouseoverFadeInTimeSlider)
    KongConfig_UpdateTriggerSlider(KongConfig_MouseoverFadeOutTimeSlider)
    
end

function KongConfig_UpdatePower(power, CheckBox, UnitsComboBox, ComparisonComboBox)

    if KongConfig_FadeCheckBox:GetValue() and CheckBox:GetValue() then
    
        -- Select types based on state
        if power ~= "health" then
            for i, widget in KongConfig_PowerTypesComboBox.pullout:IterateItems() do
                if widget.type == "Dropdown-Item-Toggle" then
                
                    widget:SetUserData(true, nil)
                    widget:SetUserData(false, nil)
                    
                    for _, SelectedFrame in pairs(KongConfig_SelectedFrames) do
                        if Kong_Frames[SelectedFrame.uiFrame] then
                            widget:SetUserData((nil ~= Kong_Frames[SelectedFrame.uiFrame][power]), true)
                        end
                    end
                    
                    local set, clear = widget:GetUserData(true), widget:GetUserData(false)
                    if set and clear then
                        widget.value = nil
                        widget.check:Show()
                        SetDesaturation(widget.check, true)
                    else
                        KongConfig_PowerTypesComboBox:SetItemValue(widget.userdata.value, set)
                        SetDesaturation(widget.check, false)
                    end
                end
            end
            
            if KongConfig_PowerTypesComboBox.open then
                KongConfig_PowerTypesComboBox.pullout:Open("TOPLEFT", KongConfig_PowerTypesComboBox.frame, "BOTTOMLEFT", 0, KongConfig_PowerTypesComboBox.label:IsShown() and -2 or 0)
            end
        end
        
        -- Select units based on state
        for i, widget in UnitsComboBox.pullout:IterateItems() do
            if widget.type == "Dropdown-Item-Toggle" then
            
                widget:SetUserData(true, nil)
                widget:SetUserData(false, nil)
                
                for _, SelectedFrame in pairs(KongConfig_SelectedFrames) do
                    if Kong_Frames[SelectedFrame.uiFrame] then
                        widget:SetUserData((nil ~= Kong_Frames[SelectedFrame.uiFrame][power]) and (nil ~= Kong_Frames[SelectedFrame.uiFrame][power].Units[widget:GetText()]), true)
                    end
                end
                
                local set, clear = widget:GetUserData(true), widget:GetUserData(false)
                if set and clear then
                    widget.value = nil
                    widget.check:Show()
                    SetDesaturation(widget.check, true)
                else
                    UnitsComboBox:SetItemValue(widget.userdata.value, set)
                    SetDesaturation(widget.check, false)
                end
            end
        end
        
        if UnitsComboBox.open then
            UnitsComboBox.pullout:Open("TOPLEFT", UnitsComboBox.frame, "BOTTOMLEFT", 0, UnitsComboBox.label:IsShown() and -2 or 0)
        end
        
        -- Select < and > based on state
        for i, widget in ComparisonComboBox.pullout:IterateItems() do
            if widget.type == "Dropdown-Item-Toggle" then
            
                widget:SetUserData(true, nil)
                widget:SetUserData(false, nil)
                
                for _, SelectedFrame in pairs(KongConfig_SelectedFrames) do
                    if Kong_Frames[SelectedFrame.uiFrame] then
                        widget:SetUserData((nil ~= Kong_Frames[SelectedFrame.uiFrame][power]) and 
                            ((widget:GetText()=="<") == Kong_Frames[SelectedFrame.uiFrame][power].lessThan), true)
                    end
                end
                
                local set, clear = widget:GetUserData(true), widget:GetUserData(false)

                if set and clear then
                    widget:SetValue(nil)
                    widget.check:Show()
                    SetDesaturation(widget.check, true)
                    ComparisonComboBox:SetText("")
                elseif set then
                    widget:SetValue(true)
                    SetDesaturation(widget.check, false)
                    ComparisonComboBox:SetText(widget:GetText())
                elseif clear then
                    widget:SetValue(false)
                    SetDesaturation(widget.check, false)
                end
            end
        end

        if ComparisonComboBox.open then
            ComparisonComboBox.pullout:Open("TOPLEFT", ComparisonComboBox.frame, "BOTTOMLEFT", 0, ComparisonComboBox.label:IsShown() and -2 or 0)
        end
    else
        UnitsComboBox.pullout:Close()
        ComparisonComboBox.pullout:Close()
    end
end

function KongConfig_UpdateGroups()

    if KongConfig_FadeCheckBox:GetValue() then
        -- Populate the group pulldown
        local groups = {}
        for name in pairs(Kong_Settings.Groups) do 
            groups[name] = name
        end
        KongConfig_GroupsComboBox:SetList(groups)
        
        -- Select items based on state
        for i, widget in KongConfig_GroupsComboBox.pullout:IterateItems() do
            if widget.type == "Dropdown-Item-Toggle" then
            
                widget:SetUserData(true, nil)
                widget:SetUserData(false, nil)
                
                for _, SelectedFrame in pairs(KongConfig_SelectedFrames) do
                    if Kong_Frames[SelectedFrame.uiFrame] then
                        
                        widget:SetUserData(nil ~= 
                            Kong_Settings.Groups[widget:GetText()][Kong_Frames[SelectedFrame.uiFrame].index], true)
                    end
                end
                
                local set, clear = widget:GetUserData(true), widget:GetUserData(false)
                if set and clear then
                    widget.value = nil
                    widget.check:Show()
                    SetDesaturation(widget.check, true)
                else
                    KongConfig_GroupsComboBox:SetItemValue(widget:GetText(), set)
                    SetDesaturation(widget.check, false)
                end
            end
        end
        
        if KongConfig_GroupsComboBox.open then
            KongConfig_GroupsComboBox.pullout:Open("TOPLEFT", KongConfig_GroupsComboBox.frame, "BOTTOMLEFT", 0, KongConfig_GroupsComboBox.label:IsShown() and -2 or 0)
        end
    else
        KongConfig_GroupsComboBox:SetList({})
        KongConfig_GroupsComboBox.pullout:Close()
    end
    
    KongConfig_NewGroupEditBox.editbox:ClearFocus()
    KongConfig_NewGroupEditBox:SetText("")
end

function KongConfig_UpdateMacro()

    local macroText = nil
    local nonmacro = false
    local conflicting = false
    for _, SelectedFrame in pairs(KongConfig_SelectedFrames) do
        
        if Kong_Frames[SelectedFrame.uiFrame] and Kong_Frames[SelectedFrame.uiFrame].macro then
            if not macroText then
                macroText = Kong_Frames[SelectedFrame.uiFrame].macro.condition
            elseif macroText ~= Kong_Frames[SelectedFrame.uiFrame].macro.condition then
                conflicting = true
                break
            end
        else 
            nonmacro = true
        end
    end
    
    if not macroText then
        KongConfig_MacroEditBox:SetText("")
        KongConfig_MacroEditBox:SetUserData(VALID, false)
    elseif conflicting then
        KongConfig_MacroEditBox:SetText("|c88888888".."<multiple different conditions>".."|r")
        KongConfig_MacroEditBox:SetUserData(VALID, false)
    elseif nonmacro then
        KongConfig_MacroEditBox:SetText("|c88888888"..macroText.."|r")
        KongConfig_MacroEditBox:SetUserData(VALID, true)
    else
        KongConfig_MacroEditBox:SetText(macroText)
        KongConfig_MacroEditBox:SetUserData(VALID, true)
    end
    
    KongConfig_MacroEditBox.editbox:ClearFocus()
end

function KongConfig_UpdateAdvanced()
    
    local selectedFrame = next(KongConfig_SelectedFrames)
    if selectedFrame then
        if not next(KongConfig_SelectedFrames, selectedFrame) then
        
            KongConfig_PersistAsDropDown:SetText(_G[selectedFrame:GetName().."Title"]:GetText())
        else
            KongConfig_PersistAsDropDown:SetText("Too many widgets selected");
            KongConfig_PersistAsDropDown.pullout:Close()
        end
    else
        KongConfig_PersistAsDropDown:SetText("");
        KongConfig_PersistAsDropDown.pullout:Close()
    end

    if not KongConfig_FadeCheckBox:GetValue() then
        KongConfig_PersistAsDropDown.pullout:Close()
    end
end

function KongConfig_SetCheckBox(checkbox)
    
    local set, clear = checkbox:GetUserData(true), checkbox:GetUserData(false)
    if set and clear then
        checkbox:SetTriState(true)
        checkbox:SetValue(nil)
    else
        checkbox:SetTriState(false)
        checkbox:SetValue(set == true)
    end
end

function KongConfig_UpdateTriggerSlider(slider)

    slider:SetValue((slider.min+slider.max)/2)
    slider.editbox:SetText(SLIDER_VALUE_NA)
            
    local trigger, field = slider:GetUserData(TRIGGER), slider:GetUserData(FIELD)
    local sliderValue, currentValue
    for _, SelectedFrame in pairs(KongConfig_SelectedFrames) do
        
        if Kong_Frames[SelectedFrame.uiFrame] and Kong_Frames[SelectedFrame.uiFrame][trigger] then
            currentValue = Kong_Frames[SelectedFrame.uiFrame][trigger][field]
        else
            slider:SetValue((slider.min+slider.max)/2)
            slider.editbox:SetText(SLIDER_VALUE_NA)
            break
        end
        
        if not sliderValue then
            sliderValue = currentValue
            slider:SetValue(sliderValue)
        elseif sliderValue ~= currentValue then
            slider:SetValue((slider.min+slider.max)/2)
            slider.editbox:SetText(SLIDER_VALUE_NA)
            break
        end
    end
end
 
function KongConfig_SliderCheckBox_OnValueChanged(self) 
    
    KongConfig:SetStatusText("")

    local trigger, field = self:GetUserData(TRIGGER), self:GetUserData(FIELD)
    
    for frame in pairs(KongConfig_SelectedFrames) do
        if self:GetValue() then
            Kong_Frames[frame.uiFrame][trigger][field] = 
                Kong_Frames[frame.uiFrame][trigger][field]
        else
            Kong_Frames[frame.uiFrame][trigger][field] = nil
        end
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_TriggerSlider_OnMouseUp(self, _, value)
    
    KongConfig:SetStatusText("")

    self:SetValue(value)
    
    local trigger, field = self:GetUserData(TRIGGER), self:GetUserData(FIELD)
    for frame in pairs(KongConfig_SelectedFrames) do
        Kong_Frames[frame.uiFrame][trigger][field] = value
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_FadeCheckBox_OnValueChanged() 
    
    KongConfig:SetStatusText("")

    local hide = KongConfig_FadeCheckBox:GetValue()
    if hide then
        for frame in pairs(KongConfig_SelectedFrames) do
            if not Kong_Frames[frame.uiFrame] then
                Kong_RegisterFrame(frame.uiFrame)
                Kong_Frames[frame.uiFrame].config = Kong_TriggerFactory.Create(ConfigTriggerDefaults)
                Kong_FadeIn(frame.uiFrame, Kong_Frames[frame.uiFrame].config)
            end
        end
    else
        for frame in pairs(KongConfig_SelectedFrames) do
            if Kong_Frames[frame.uiFrame] then
                Kong_UnregisterFrame(frame.uiFrame)
            end
        end
    end

    KongConfig_UpdateComponents()
    KongConfig_AutoExpandAndCollapse()
end

function KongConfig_ShowBooleanRadioButton_OnValueChanged(self) 
    
    KongConfig:SetStatusText("")
    
    local show = self:GetValue()
    
    for frame in pairs(KongConfig_SelectedFrames) do
        Kong_SetFrameBooleanVisibility(frame.uiFrame, self:GetUserData(TRIGGER), show)
        Kong_SetFrameBooleanVisibility(frame.uiFrame, NegateBoolean(self:GetUserData(TRIGGER)), false)
    end
    
    self.parent.parent:SetCollapsed(show == false)
    KongConfig_UpdateComponents()
end

function KongConfig_PowerShowCheckBox_OnValueChanged(self)

    KongConfig:SetStatusText("")
    
    local show = self:GetValue()
    
    for frame in pairs(KongConfig_SelectedFrames) do
        if show then
            Kong_SetPowerVisibility(frame.uiFrame, self:GetUserData(TRIGGER), {player=false}, true, 1)
        else
            Kong_ClearPowerVisibility(frame.uiFrame, self:GetUserData(TRIGGER))
        end
    end
    
    KongConfig_HealthGroup:SetCollapsed(show == false) -- FIXME could be power
    KongConfig_UpdateComponents()
end

function KongConfig_PowerTypesComboBox_OnValueChanged(self, _, index, checked)

    KongConfig:SetStatusText("")

    for frame in pairs(KongConfig_SelectedFrames) do
        local Trigger = Kong_Frames[frame.uiFrame][self:GetUserData(TRIGGER)]
        Kong_SetPowerVisibility(frame.uiFrame, self:GetUserData(TRIGGER), Trigger.Units, Trigger.lessThan, Trigger.threshold)
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_PowerUnitsComboBox_OnValueChanged(self, _, index, checked)

    KongConfig:SetStatusText("")

    for frame in pairs(KongConfig_SelectedFrames) do
        local Trigger = Kong_Frames[frame.uiFrame][self:GetUserData(TRIGGER)]
        local Units = {}
        for unit in pairs(Trigger.Units) do
            Units[unit] = false
        end
        if checked then
            Units[Kong_PowerUnits[index]] = false
        else
            Units[Kong_PowerUnits[index]] = nil
        end
        Kong_SetPowerVisibility(frame.uiFrame, self:GetUserData(TRIGGER), Units, Trigger.lessThan, Trigger.threshold)
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_PowerComparisonComboBox_OnValueChanged(self, _, index)

    KongConfig:SetStatusText("")
    
    for frame in pairs(KongConfig_SelectedFrames) do
        local Trigger = Kong_Frames[frame.uiFrame][self:GetUserData(TRIGGER)]
        Kong_SetPowerVisibility(frame.uiFrame, self:GetUserData(TRIGGER), Trigger.Units, 1==index, Trigger.threshold)
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_PowerThresholdSlider_OnMouseUp(self, _, value)
   
    KongConfig:SetStatusText("")

    self:SetValue(value)
    
    for frame in pairs(KongConfig_SelectedFrames) do
        local Trigger = Kong_Frames[frame.uiFrame][self:GetUserData(TRIGGER)]
        Kong_SetPowerVisibility(frame.uiFrame, self:GetUserData(TRIGGER), Trigger.Units, Trigger.lessThan, value)
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_GroupsComboBox_OnValueChanged(self, _, group, checked)
    
    KongConfig:SetStatusText("")

    for frame in pairs(KongConfig_SelectedFrames) do
        if checked then
            Kong_AddFrameToGroup(frame.uiFrame, group)
        else
            Kong_RemoveFrameFromGroup(frame.uiFrame, group)
        end
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_NewGroupEditBox_OnEnterPressed(self, _, text)
    
    if text == "" then
        KongConfig_Error("Group name cannot be empty.")
        return
    else
        KongConfig:SetStatusText("")
    end
    
    for frame in pairs(KongConfig_SelectedFrames) do
        Kong_AddFrameToGroup(frame.uiFrame, string.lower(text))
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_MacroShowCheckBox_OnValueChanged(self) 
    
    KongConfig:SetStatusText("")

    local show = self:GetValue()
    
    if show then
        KongConfig_MacroEditBox:SetDisabled(false)
        if KongConfig_MacroEditBox:GetUserData(VALID) then
            KongConfig_MacroEditBox:Fire("OnEnterPressed", KongConfig_MacroEditBox:GetText())
        else
            KongConfig_MacroEditBox.editbox:SetFocus()
        end
    else
        for frame in pairs(KongConfig_SelectedFrames) do
            Kong_ClearMacro(frame.uiFrame)
        end
        KongConfig_UpdateComponents()
    end
    KongConfig_MacroGroup:SetCollapsed(show == false)
end

function KongConfig_MacroEditBox_OnEnterPressed(self, _, text)
    
    KongConfig:SetStatusText("")
    
    for frame in pairs(KongConfig_SelectedFrames) do
        if not Kong_SetMacro(frame.uiFrame, string.lower(text)) then
            Kong_Error("Invalid macro condition %q (ex: |cFF33FF99[mounted]|r ).", text);
            self:SetText("")
            break
        end
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_OverrideAlphaCheckBox_OnValueChanged(self)
    
    KongConfig:SetStatusText("")
    
    local show = self:GetValue()

    for frame in pairs(KongConfig_SelectedFrames) do
        Kong_OverrideAlpha(frame.uiFrame, show)
        Kong_Frames[frame.uiFrame].overrideAlpha = show
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_DisableDrawCheckBox_OnValueChanged(self)
    
    KongConfig:SetStatusText("")
    
    local show = self:GetValue()

    for frame in pairs(KongConfig_SelectedFrames) do
        Kong_Frames[frame.uiFrame].disableDrawWhenHidden = show
    end
    
    KongConfig_UpdateComponents()
end

function KongConfig_PersistAsDropDown_OnClick(self, button, down)

    KongConfig_PersistAsDropDown.pullout:SetWidth(KongConfig_PersistAsDropDown.frame:GetWidth() - 30);
    
    -- Scan memory if a new frame was selected since last time
    local Frame = next(KongConfig_SelectedFrames)
    if Frame ~= KongConfig_PersistAsDropDown:GetUserData(FRAME) then
        KongConfig_PersistAsDropDown:SetUserData(FRAME, Frame)
        KongConfig_PersistAsDropDown:SetList({})
        KongConfig_PersistAsCoroutine = coroutine.create(KongConfig_PersistableFramePathSearch)
        local status, err = coroutine.resume(KongConfig_PersistAsCoroutine, Frame.uiFrame)
        if not status then
            error(err)
        end
    end
end

function KongConfig_PersistAsComboBox_OnValueChanged(self, _, code)

    KongConfig:SetStatusText("")
    
    local Frame = next(KongConfig_SelectedFrames)
    
    Kong_RenameFrame(Frame.uiFrame, code)
    _G[Frame:GetName().."Title"]:SetText(Debracket(code))
    
    KongConfig_UpdateComponents()
end

function KongConfig_UpdateTooltip(self, event)
    
    if event == "OnEnter" then
        GameTooltip:SetOwner(self:GetUserData(OWNER) or self.frame, "ANCHOR_TOP")
        GameTooltip:AddLine(self:GetUserData(TITLE) or self.text:GetText())
        
        GameTooltip:AddLine(self:GetUserData(TOOLTIP) or 
            self:GetUserData(TOOLTIP..self:GetUserData(TRIGGER)), 1,1,1,1,1)
        
        GameTooltip:Show()
    else
        GameTooltip:Hide()
    end
end